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 {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < 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 {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var minDistance = Double.greatestFiniteMagnitude
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
}
}
}
return minDistance < threshold
}
```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 {
var minDistance = Double.greatestFiniteMagnitude
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
}
}
}
return minDistance < threshold
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```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 {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```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 {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```
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
}
```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
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
result = true
break
}
}
}
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 {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
result = true
break
}
}
}
return result
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var numbers = numbers
numbers.sort()
for i in 0..<numbers.count - 1 {
if numbers[i + 1] - numbers[i] < 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 {
var numbers = numbers
numbers.sort()
for i in 0..<numbers.count - 1 {
if numbers[i + 1] - numbers[i] < threshold {
return true
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
}
}
}
return close
}
```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 {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
}
}
}
return close
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```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 {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```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 {
var close = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
close = true
break
}
}
if close {
break
}
}
return close
}
```
func separateParenGroups(parenString: String) -> [String] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [String]()
var current = ""
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
if stack.isEmpty {
result.append(current)
current = ""
} else {
current = stack.removeLast() + current
}
} else {
current += String(char)
}
}
if!current.isEmpty {
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 stack = [String]()
var current = ""
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
if stack.isEmpty {
result.append(current)
current = ""
} else {
current = stack.removeLast() + current
}
} else {
current += String(char)
}
}
if!current.isEmpty {
result.append(current)
}
return result
}
```
if!current.isEmpty { // expected expression, var, or let in 'if' condition
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [String]()
var current = ""
for char in parenString {
if char == "(" {
if current.count > 0 {
stack.append(current)
current = ""
}
stack.append("(")
} else if char == ")" {
if current.count > 0 {
stack.append(current)
current = ""
}
if stack.count > 0 {
stack[stack.count - 1] += ")"
current = stack.removeLast()
}
} else {
current += String(char)
}
}
if current.count > 0 {
stack.append(current)
}
for item in stack {
result.append(item)
}
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 stack = [String]()
var current = ""
for char in parenString {
if char == "(" {
if current.count > 0 {
stack.append(current)
current = ""
}
stack.append("(")
} else if char == ")" {
if current.count > 0 {
stack.append(current)
current = ""
}
if stack.count > 0 {
stack[stack.count - 1] += ")"
current = stack.removeLast()
}
} else {
current += String(char)
}
}
if current.count > 0 {
stack.append(current)
}
for item in stack {
result.append(item)
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [String]()
var current = ""
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
if stack.isEmpty {
result.append(current)
current = ""
} else {
current = stack.removeLast() + current
}
} else {
current += String(char)
}
}
if!current.isEmpty {
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 stack = [String]()
var current = ""
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
if stack.isEmpty {
result.append(current)
current = ""
} else {
current = stack.removeLast() + current
}
} else {
current += String(char)
}
}
if!current.isEmpty {
result.append(current)
}
return result
}
```
if!current.isEmpty { // expected expression, var, or let in 'if' condition
func separateParenGroups(parenString: String) -> [String] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[String]'
func truncateNumber(number: Double) -> Double {
return number - floor(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 - floor(number)
}
```
func truncateNumber(number: Double) -> Double {
return number - floor(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 - floor(number)
}
```
func truncateNumber(number: Double) -> Double {
return number - Double(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 - Double(Int(number))
}
```
func truncateNumber(number: Double) -> Double {
return number - floor(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 - floor(number)
}
```
func truncateNumber(number: Double) -> Double {
return number - Double(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 - Double(Int(number))
}
```
func truncateNumber(number: Double) -> Double {
return number - Double(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 - Double(Int(number))
}
```
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - Double(integerPart)
return decimalPart
}
```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 {
let integerPart = Int(number)
let decimalPart = number - Double(integerPart)
return decimalPart
}
```
func truncateNumber(number: Double) -> Double {
return number - Double(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 - Double(Int(number))
}
```
func truncateNumber(number: Double) -> Double {
return number - floor(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 - floor(number)
}
```
func truncateNumber(number: Double) -> Double {
return number - Double(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 - Double(Int(number))
}
```
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
}
```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
}
```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 meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```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 = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```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 = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```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 = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```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 = mean(numbers: numbers)
let differences = numbers.map { abs($0 - mean) }
return mean(numbers: differences)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(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 = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(numbers.count)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let sum = numbers.reduce(0.0) { $0 + abs($1 - mean) }
return sum / Double(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 = mean(numbers: numbers)
let sum = numbers.reduce(0.0) { $0 + abs($1 - mean) }
return sum / Double(numbers.count)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(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 = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(numbers.count)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(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 = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(numbers.count)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(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 = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(numbers.count)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(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 = mean(numbers: numbers)
let sum = numbers.reduce(0.0, { $0 + abs($1 - mean) })
return sum / Double(numbers.count)
}
```
let mean = mean(numbers: numbers) // use of local variable 'mean' before its declaration
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
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 (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Implement this function.
}
```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] {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return '[Int]'
func parseNestedParens(parenString: String) -> [Int] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[Int]'
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
var max = 0
for char in parenString {
if char == "(" {
stack.append(max)
max = 0
} else if char == ")" {
max += 1
result.append(max)
max = stack.removeLast()
}
}
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 max = 0
for char in parenString {
if char == "(" {
stack.append(max)
max = 0
} else if char == ")" {
max += 1
result.append(max)
max = stack.removeLast()
}
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Implement this function.
return []
}
```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] {
// TODO: Implement this function.
return []
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepths = [Int]()
var depth = 0
var maxDepth = 0
for char in parenString {
if char == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if char == ")" {
depth -= 1
}
}
maxDepths.append(maxDepth)
return maxDepths
}
```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 maxDepths = [Int]()
var depth = 0
var maxDepth = 0
for char in parenString {
if char == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if char == ")" {
depth -= 1
}
}
maxDepths.append(maxDepth)
return maxDepths
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var currentDepth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
currentDepth += 1
maxDepth = max(maxDepth, currentDepth)
} else if char == ")" {
currentDepth -= 1
}
}
result.append(maxDepth)
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 maxDepth = 0
var currentDepth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
currentDepth += 1
maxDepth = max(maxDepth, currentDepth)
} else if char == ")" {
currentDepth -= 1
}
}
result.append(maxDepth)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepths = [Int]()
var depth = 0
var maxDepth = 0
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
}
maxDepths.append(maxDepth)
return maxDepths
}
```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 maxDepths = [Int]()
var depth = 0
var maxDepth = 0
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
}
maxDepths.append(maxDepth)
return maxDepths
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if char == ")" {
depth -= 1
}
}
for _ in 0..<parenString.count {
result.append(maxDepth)
}
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 maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if char == ")" {
depth -= 1
}
}
for _ in 0..<parenString.count {
result.append(maxDepth)
}
return result
}
```
// XCTAssertTrue failed
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) }
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
```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] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
```
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) }
}
```
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] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
```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] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result: [String] = []
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
```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] {
var result: [String] = []
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
```
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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```
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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```
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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```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) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
max = max < number? number : 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 = numbers[0]
for number in numbers {
result.append(max)
max = max < number? number : max
}
return result
}
```
max = max < number? number : max // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
max = max < number? number : max // expected expression
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // cannot assign value of type 'Bool' to type 'Int'
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // expression of type 'Int' is unused
max = max < number? number : max // cannot use optional chaining on non-optional value of type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers.first!
for number in numbers {
result.append(max)
max = max < number? number : 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 = numbers.first!
for number in numbers {
result.append(max)
max = max < number? number : max
}
return result
}
```
max = max < number? number : max // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
max = max < number? number : max // expected expression
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // cannot assign value of type 'Bool' to type 'Int'
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // expression of type 'Int' is unused
max = max < number? number : max // cannot use optional chaining on non-optional value of type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
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 = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
max = max < number? number : 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 = numbers[0]
for number in numbers {
result.append(max)
max = max < number? number : max
}
return result
}
```
max = max < number? number : max // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
max = max < number? number : max // expected expression
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // cannot assign value of type 'Bool' to type 'Int'
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // expression of type 'Int' is unused
max = max < number? number : max // cannot use optional chaining on non-optional value of type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
max = max < number? number : max
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 = 0
for number in numbers {
max = max < number? number : max
result.append(max)
}
return result
}
```
max = max < number? number : max // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
max = max < number? number : max // expected expression
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // cannot assign value of type 'Bool' to type 'Int'
max = max < number? number : max // consecutive statements on a line must be separated by ';'
max = max < number? number : max // expression of type 'Int' is unused
max = max < number? number : max // cannot use optional chaining on non-optional value of type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
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 = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
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 = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
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 = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
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 = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result: [Int] = []
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
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 = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// Fatal error: Index out of range
func makePalindrome(string: String) -> String {
let reversed = String(string.characters.reversed())
let reversedPrefix = string.characters.prefix(while: { $0 == reversed.characters.first! })
let reversedSuffix = reversed.characters.suffix(while: { $0 == string.characters.first! })
return String(reversedPrefix) + string + String(reversedSuffix)
}
```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.characters.reversed())
let reversedPrefix = string.characters.prefix(while: { $0 == reversed.characters.first! })
let reversedSuffix = reversed.characters.suffix(while: { $0 == string.characters.first! })
return String(reversedPrefix) + string + String(reversedSuffix)
}
```
let reversed = String(string.characters.reversed()) // 'characters' is unavailable: Please use String directly
let reversedPrefix = string.characters.prefix(while: { $0 == reversed.characters.first! }) // 'characters' is unavailable: Please use String directly
let reversedPrefix = string.characters.prefix(while: { $0 == reversed.characters.first! }) // 'characters' is unavailable: Please use String directly
let reversedSuffix = reversed.characters.suffix(while: { $0 == string.characters.first! }) // no exact matches in call to instance method 'suffix'
func makePalindrome(string: String) -> String {
let reversed = String(string.characters.reversed())
let reversedPrefix = string.characters.dropLast(reversed.characters.count)
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(string.characters.reversed())
let reversedPrefix = string.characters.dropLast(reversed.characters.count)
return String(reversedPrefix) + reversed
}
```
let reversed = String(string.characters.reversed()) // 'characters' is unavailable: Please use String directly
let reversedPrefix = string.characters.dropLast(reversed.characters.count) // 'characters' is unavailable: Please use String directly
let reversedPrefix = string.characters.dropLast(reversed.characters.count) // 'characters' is unavailable: Please use String directly
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let longestPalindrome = longestPalindrome(string: string + reversed)
let prefix = string[string.startIndex..<longestPalindrome.startIndex]
return String(prefix.reversed()) + string + String(reversed[reversed.startIndex..<longestPalindrome.endIndex])
}
```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 longestPalindrome = longestPalindrome(string: string + reversed)
let prefix = string[string.startIndex..<longestPalindrome.startIndex]
return String(prefix.reversed()) + string + String(reversed[reversed.startIndex..<longestPalindrome.endIndex])
}
```
let longestPalindrome = longestPalindrome(string: string + reversed) // use of local variable 'longestPalindrome' before its declaration
func makePalindrome(string: String) -> String {
let reversed = String(string.characters.reversed())
let reversedPrefix = string.characters.dropLast(reversed.characters.count)
let reversedPrefixString = String(reversedPrefix)
return reversedPrefixString + 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(string.characters.reversed())
let reversedPrefix = string.characters.dropLast(reversed.characters.count)
let reversedPrefixString = String(reversedPrefix)
return reversedPrefixString + reversed
}
```
let reversed = String(string.characters.reversed()) // 'characters' is unavailable: Please use String directly
let reversedPrefix = string.characters.dropLast(reversed.characters.count) // 'characters' is unavailable: Please use String directly
let reversedPrefix = string.characters.dropLast(reversed.characters.count) // 'characters' is unavailable: Please use String directly
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let reversedPrefix = reversed.prefix(string.count)
let reversedSuffix = reversed.suffix(string.count)
let reversedPrefixString = String(reversedPrefix)
let reversedSuffixString = String(reversedSuffix)
let reversedPrefixStringReversed = String(reversedPrefixString.reversed())
return reversedPrefixStringReversed + reversedSuffixString
}
```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 reversedPrefix = reversed.prefix(string.count)
let reversedSuffix = reversed.suffix(string.count)
let reversedPrefixString = String(reversedPrefix)
let reversedSuffixString = String(reversedSuffix)
let reversedPrefixStringReversed = String(reversedPrefixString.reversed())
return reversedPrefixStringReversed + reversedSuffixString
}
```
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let reversedPrefix = reversed.prefix(string.count)
return string + String(reversedPrefix)
}
```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 reversedPrefix = reversed.prefix(string.count)
return string + String(reversedPrefix)
}
```
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
var s = string
var i = s.index(before: s.endIndex)
var j = s.index(before: i)
while i > s.startIndex && j > s.startIndex {
if s[i] == s[j] {
i = s.index(before: i)
j = s.index(before: j)
} else {
break
}
}
let prefix = String(s[s.startIndex..<i])
return prefix + String(prefix.reversed()) + s
}
```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 {
var s = string
var i = s.index(before: s.endIndex)
var j = s.index(before: i)
while i > s.startIndex && j > s.startIndex {
if s[i] == s[j] {
i = s.index(before: i)
j = s.index(before: j)
} else {
break
}
}
let prefix = String(s[s.startIndex..<i])
return prefix + String(prefix.reversed()) + s
}
```
var s = string // variable 's' was never mutated; consider changing to 'let' constant
// Fatal error: String index is out of bounds
```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 reversedPrefix = reversed.prefix(string.count)
let reversedSuffix = reversed.suffix(string.count)
let reversedPrefixString = String(reversedPrefix)
let reversedSuffixString = String(reversedSuffix)
let reversedPrefixStringReversed = String(reversedPrefixString.reversed())
let reversedSuffixStringReversed = String(reversedSuffixString.reversed())
let reversedPrefixStringReversedWithSuffix = reversedPrefixStringReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversed.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffix + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix = reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed + reversedSuffixString
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed = String(reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffix.reversed())
let reversedPrefixStringReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversedWithSuffixReversed
XCTAssertTrue(makePalindrome(string: "") == "") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "x") == "x") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "xyz") == "xyzyx") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "xyx") == "xyx") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "jerry") == "jerryrrej") // cannot find 'makePalindrome' in scope
```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.characters.reversed())
let reversedPrefix = reversed.substring(to: string.endIndex)
let reversedSuffix = reversed.substring(from: string.startIndex)
let reversedPrefixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefix.characters.count)
let reversedSuffixIndex = string.characters.index(string.endIndex, offsetBy: -reversedSuffix.characters.count)
let reversedPrefixAndSuffix = string.substring(with: Range(uncheckedBounds: (lower: string.startIndex, upper: reversedSuffixIndex)))
let reversedPrefixAndSuffixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffix = reversedPrefixAndSuffix + reversedSuffix
let reversedPrefixAndSuffixAndReversedSuffixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefix = reversedPrefixAndSuffixAndReversedSuffix + reversedPrefix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffix = reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefix + reversedSuffix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefix = reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffix + reversedPrefix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffix = reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefix + reversedSuffix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefix = reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffix + reversedPrefix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffixAndReversedPrefix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffix = reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffixAndReversedPrefix + reversedSuffix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffix.characters.count)
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefix = reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffix + reversedPrefix
let reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefixIndex = string.characters.index(string.startIndex, offsetBy: reversedPrefixAndSuffixAndReversedSuffixAndReversedPrefixAndReversedPrefixAndReversedSuffixAndReversedPrefixAndReversedSuffixAndReversedPrefix.characters.count)
let reversedPrefixAndSuffix
XCTAssertTrue(makePalindrome(string: "") == "") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "x") == "x") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "xyz") == "xyzyx") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "xyx") == "xyx") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "jerry") == "jerryrrej") // cannot find 'makePalindrome' in scope
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let reversedPrefix = reversed.prefix(string.count)
let reversedSuffix = reversed.suffix(string.count)
let reversedPrefixString = String(reversedPrefix)
let reversedSuffixString = String(reversedSuffix)
let reversedPrefixStringReversed = String(reversedPrefixString.reversed())
return reversedPrefixStringReversed + reversedSuffixString
}
```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 reversedPrefix = reversed.prefix(string.count)
let reversedSuffix = reversed.suffix(string.count)
let reversedPrefixString = String(reversedPrefix)
let reversedSuffixString = String(reversedSuffix)
let reversedPrefixStringReversed = String(reversedPrefixString.reversed())
return reversedPrefixStringReversed + reversedSuffixString
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
var result = ""
for (i, char) in a.enumerated() {
let charB = b.index(b.startIndex, offsetBy: i)
let charB = b[charB]
if char == charB {
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, char) in a.enumerated() {
let charB = b.index(b.startIndex, offsetBy: i)
let charB = b[charB]
if char == charB {
result += "0"
} else {
result += "1"
}
}
return result
}
```
let charB = b[charB] // invalid redeclaration of 'charB'
func stringXor(a: String, b: String) -> String {
var result = ""
for (index, char) in a.enumerated() {
let charB = b.index(b.startIndex, offsetBy: index)
if char == charB {
result.append("0")
} else {
result.append("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 (index, char) in a.enumerated() {
let charB = b.index(b.startIndex, offsetBy: index)
if char == charB {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
if char == charB { // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String.Index'
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0)
result += String(xor)
}
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 {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0)
result += String(xor)
}
return result
}
```
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // binary operator '==' cannot be applied to operands of type 'Character' and 'String?'
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // cannot use optional chaining on non-optional value of type 'String'
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // binary operator '==' cannot be applied to operands of type 'Character' and 'String?'
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // cannot use optional chaining on non-optional value of type 'String'
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // expected ',' separator
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // binary operator '^' cannot be applied to two '(Bool, Int)' operands
let xor = (charA == "1"? 1 : 0) ^ (charB == "1"? 1 : 0) // expected ',' separator
func stringXor(a: String, b: String) -> String {
var result = ""
for (i, char) in a.enumerated() {
let char2 = b.index(b.startIndex, offsetBy: i)
let char2 = b[char2]
if char == char2 {
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, char) in a.enumerated() {
let char2 = b.index(b.startIndex, offsetBy: i)
let char2 = b[char2]
if char == char2 {
result += "0"
} else {
result += "1"
}
}
return result
}
```
let char2 = b[char2] // invalid redeclaration of 'char2'
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
if charA == charB {
result.append("0")
} else {
result.append("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 {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
if charA == charB {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[a.index(a.startIndex, offsetBy: i)] == b[b.index(b.startIndex, offsetBy: 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[a.index(a.startIndex, offsetBy: i)] == b[b.index(b.startIndex, offsetBy: i)] {
result += "0"
} else {
result += "1"
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
if charA == charB {
result.append("0")
} else {
result.append("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 {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
if charA == charB {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
if charA == charB {
result.append("0")
} else {
result.append("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 {
let charA = a[a.index(a.startIndex, offsetBy: i)]
let charB = b[b.index(b.startIndex, offsetBy: i)]
if charA == charB {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
if aChar == bChar {
result.append("0")
} else {
result.append("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 {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
if aChar == bChar {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[a.index(a.startIndex, offsetBy: i)] == b[b.index(b.startIndex, offsetBy: i)] {
result.append("0")
} else {
result.append("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[a.index(a.startIndex, offsetBy: i)] == b[b.index(b.startIndex, offsetBy: i)] {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func longest(strings: [String]) -> String? {
// Your code here
}
```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? {
// Your code here
}
```
} // missing return in global function expected to return 'String?'
func longest(strings: [String]) -> String? {
var longest = strings.first
for string in strings {
if string.count > longest?.count?? 0 {
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? {
var longest = strings.first
for string in strings {
if string.count > longest?.count?? 0 {
longest = string
}
}
return longest
}
```
if string.count > longest?.count?? 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if string.count > longest?.count?? 0 { // expected '{' after 'if' condition
if string.count > longest?.count?? 0 { // cannot use optional chaining on non-optional value of type 'Int'
if string.count > longest?.count?? 0 { // cannot use optional chaining on non-optional value of type 'Int'
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
var longest = strings.first
for string in strings {
if string.count > longest?.count?? 0 {
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? {
var longest = strings.first
for string in strings {
if string.count > longest?.count?? 0 {
longest = string
}
}
return longest
}
```
if string.count > longest?.count?? 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if string.count > longest?.count?? 0 { // expected '{' after 'if' condition
if string.count > longest?.count?? 0 { // cannot use optional chaining on non-optional value of type 'Int'
if string.count > longest?.count?? 0 { // cannot use optional chaining on non-optional value of type 'Int'
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return nil
}
```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 nil
}
```
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 || b == 0 {
return 0
}
if a == b {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
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 || b == 0 {
return 0
}
if a == b {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: a, b: b - a)
}
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 || b == 0 {
return 0
}
if a == b {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
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 || b == 0 {
return 0
}
if a == b {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: a, b: b - a)
}
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```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 b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
} else if b == 0 {
return a
} else {
return greatestCommonDivisor(a: a % b, 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
} else if b == 0 {
return a
} else {
return greatestCommonDivisor(a: a % b, b: b % a)
}
}
```
func allPrefixes(string: String) -> [String] {
var result: [String] = []
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result: [String] = []
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result: [String] = []
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result: [String] = []
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result: [String] = []
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result: [String] = []
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result: [String] = []
for i in 0...string.count {
result.append(String(string.prefix(i)))
}
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 result: [String] = []
for i in 0...string.count {
result.append(String(string.prefix(i)))
}
return result
}
```
// XCTAssertTrue failed
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
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 result = [String]()
for i in 0...string.count {
result.append(string.prefix(i))
}
return result
}
```
result.append(string.prefix(i)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
result.append(String(string.prefix(i)))
}
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 result = [String]()
for i in 0...string.count {
result.append(String(string.prefix(i)))
}
return result
}
```
// 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
}
```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
}
```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
}
```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
}
```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
}
```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
}
```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
}
```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
}
```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
}
```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 countDistinctCharacters(string: String) -> Int {
return Set(string).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).count
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var count = 0
var set = Set<Character>()
for char in string {
if!set.contains(char) {
set.insert(char)
count += 1
}
}
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 set = Set<Character>()
for char in string {
if!set.contains(char) {
set.insert(char)
count += 1
}
}
return count
}
```
if!set.contains(char) { // expected expression, var, or let in 'if' condition
func countDistinctCharacters(string: String) -> Int {
var count = 0
var set = Set<Character>()
for char in string {
if!set.contains(char) {
count += 1
set.insert(char)
}
}
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 set = Set<Character>()
for char in string {
if!set.contains(char) {
count += 1
set.insert(char)
}
}
return count
}
```
if!set.contains(char) { // expected expression, var, or let in 'if' condition
func countDistinctCharacters(string: String) -> Int {
var count = 0
var characters = Set<Character>()
for character in string {
if!characters.contains(character) {
count += 1
characters.insert(character)
}
}
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 characters = Set<Character>()
for character in string {
if!characters.contains(character) {
count += 1
characters.insert(character)
}
}
return count
}
```
if!characters.contains(character) { // expected expression, var, or let in 'if' condition
func countDistinctCharacters(string: String) -> Int {
// TODO: Write your code here
}
```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 {
// TODO: Write your code here
}
```
} // missing return in global function expected to return 'Int'
func countDistinctCharacters(string: String) -> Int {
var count = 0
var characters = [Character]()
for char in string {
if!characters.contains(char) {
count += 1
characters.append(char)
}
}
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 characters = [Character]()
for char in string {
if!characters.contains(char) {
count += 1
characters.append(char)
}
}
return count
}
```
if!characters.contains(char) { // expected expression, var, or let in 'if' condition
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 set = Set<Character>()
for char in string {
if set.contains(char) {
continue
}
set.insert(char)
count += 1
}
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 set = Set<Character>()
for char in string {
if set.contains(char) {
continue
}
set.insert(char)
count += 1
}
return 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 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 parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
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 char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
result.append(currentBeat)
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentNote = 0
for char in musicString {
switch char {
case "o":
currentNote += 4
case "o|":
currentNote += 2
case ".|":
currentNote += 1
default:
break
}
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 currentNote = 0
for char in musicString {
switch char {
case "o":
currentNote += 4
case "o|":
currentNote += 2
case ".|":
currentNote += 1
default:
break
}
result.append(currentNote)
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 }
var result = [Int]()
var currentBeat = 0
for note in notes {
switch note {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
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] {
let notes = musicString.map { $0 }
var result = [Int]()
var currentBeat = 0
for note in notes {
switch note {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
result.append(currentBeat)
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
case ".|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
func parseMusic(musicString: String) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
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] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.components(separatedBy: " ")
var result = [Int]()
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
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.components(separatedBy: " ")
var result = [Int]()
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
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] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var note = ""
for char in musicString {
if char == "|" {
result.append(note.count)
note = ""
} else {
note.append(char)
}
}
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 note = ""
for char in musicString {
if char == "|" {
result.append(note.count)
note = ""
} else {
note.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 }
var result: [Int] = []
var currentNote = 0
for note in notes {
switch note {
case "o":
currentNote += 4
case "o|":
currentNote += 2
case ".|":
currentNote += 1
default:
break
}
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] {
let notes = musicString.map { $0 }
var result: [Int] = []
var currentNote = 0
for note in notes {
switch note {
case "o":
currentNote += 4
case "o|":
currentNote += 2
case ".|":
currentNote += 1
default:
break
}
result.append(currentNote)
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
case ".|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
func parseMusic(musicString: String) -> [Int] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
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 = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index..<string.index(index, offsetBy: substring.count)] == substring {
count += 1
}
index = string.index(index, offsetBy: 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 = string.startIndex
while index < string.endIndex {
if string[index..<string.index(index, offsetBy: substring.count)] == substring {
count += 1
}
index = string.index(index, offsetBy: 1)
}
return count
}
```
// Fatal error: String index is out of bounds
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var startIndex = string.startIndex
while let range = string.range(of: substring, options: [], range: startIndex..<string.endIndex, locale: nil) {
count += 1
startIndex = range.upperBound
}
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 startIndex = string.startIndex
while let range = string.range(of: substring, options: [], range: startIndex..<string.endIndex, locale: nil) {
count += 1
startIndex = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
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 = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
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 = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var startIndex = string.startIndex
while let range = string.range(of: substring, options: [], range: startIndex..<string.endIndex, locale: nil) {
count += 1
startIndex = range.upperBound
}
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 startIndex = string.startIndex
while let range = string.range(of: substring, options: [], range: startIndex..<string.endIndex, locale: nil) {
count += 1
startIndex = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index...] == substring {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(index, offsetBy: 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 = string.startIndex
while index < string.endIndex {
if string[index...] == substring {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(index, offsetBy: 1)
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
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 = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index..<string.index(index, offsetBy: substring.count)] == substring {
count += 1
}
index = string.index(index, offsetBy: 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 = string.startIndex
while index < string.endIndex {
if string[index..<string.index(index, offsetBy: substring.count)] == substring {
count += 1
}
index = string.index(index, offsetBy: 1)
}
return count
}
```
// Fatal error: String index is out of bounds
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
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 = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sorted = numbers.sorted()
return sorted.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 numbers = numbers.components(separatedBy: " ")
let sorted = numbers.sorted()
return sorted.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
let sortedNumbers = numberArray.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 numberArray = numbers.components(separatedBy: " ")
let sortedNumbers = numberArray.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.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 numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
let sortedArray = numberArray.sorted()
return sortedArray.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 numberArray = numbers.components(separatedBy: " ")
let sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.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 numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.split(separator: " ").map { String($0) }
let sortedNumbers = numbers.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 numbers = numbers.split(separator: " ").map { String($0) }
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.split(separator: " ")
let sortedNumbers = numbers.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 numbers = numbers.split(separator: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.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 numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.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 numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
let sortedArray = numberArray.sorted()
return sortedArray.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 numberArray = numbers.components(separatedBy: " ")
let sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Implement this function
}
```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) {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '(Double, Double)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// Your code here
}
```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) {
// Your code here
}
```
} // missing return in global function expected to return '(Double, Double)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Implement this function
}
```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) {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '(Double, Double)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Write your code here
}
```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) {
// TODO: Write your code here
}
```
} // missing return in global function expected to return '(Double, Double)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
let current = (numbers[i-1], numbers[i])
if abs(current.0 - current.1) < abs(closest.0 - closest.1) {
closest = current
}
}
return closest
}
```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 closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
let current = (numbers[i-1], numbers[i])
if abs(current.0 - current.1) < abs(closest.0 - closest.1) {
closest = current
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
if abs(numbers[i] - closest.0) < abs(closest.1 - closest.0) {
closest = (numbers[i], closest.0)
}
}
return closest
}
```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 closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
if abs(numbers[i] - closest.0) < abs(closest.1 - closest.0) {
closest = (numbers[i], closest.0)
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
for i in 0..<numbers.count - 1 {
let current = (numbers[i], numbers[i + 1])
let diff = abs(current.0 - current.1)
let closestDiff = abs(closest.0 - closest.1)
if diff < closestDiff {
closest = current
}
}
return closest
}
```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 closest = (numbers[0], numbers[1])
for i in 0..<numbers.count - 1 {
let current = (numbers[i], numbers[i + 1])
let diff = abs(current.0 - current.1)
let closestDiff = abs(closest.0 - closest.1)
if diff < closestDiff {
closest = current
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var minDiff = abs(numbers[0] - numbers[1])
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
closest = (numbers[i], numbers[j])
}
}
}
return closest
}
```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 closest = (numbers[0], numbers[1])
var minDiff = abs(numbers[0] - numbers[1])
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
closest = (numbers[i], numbers[j])
}
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
let current = (numbers[i-1], numbers[i])
if abs(current.0 - current.1) < abs(closest.0 - closest.1) {
closest = current
}
}
return closest
}
```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 closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
let current = (numbers[i-1], numbers[i])
if abs(current.0 - current.1) < abs(closest.0 - closest.1) {
closest = current
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
if abs(numbers[i] - closest.0) < abs(closest.1 - closest.0) {
closest.0 = numbers[i]
} else {
closest.1 = numbers[i]
}
}
return closest
}
```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 closest = (numbers[0], numbers[1])
for i in 1..<numbers.count {
if abs(numbers[i] - closest.0) < abs(closest.1 - closest.0) {
closest.0 = numbers[i]
} else {
closest.1 = numbers[i]
}
}
return closest
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { ($0 - 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 { ($0 - min) / range }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { ($0 - 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 { ($0 - min) / range }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
var result = [Double]()
for number in numbers {
result.append((number - min) / (max - min))
}
return result
}
```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] {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
var result = [Double]()
for number in numbers {
result.append((number - min) / (max - min))
}
return result
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
var result = [Double]()
for number in numbers {
result.append((number - min) / (max - min))
}
return result
}
```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] {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
var result = [Double]()
for number in numbers {
result.append((number - min) / (max - min))
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 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.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result = [Int]()
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```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] {
var result: [Int] = []
for value in values {
if let intValue = value as? Int {
result.append(intValue)
}
}
return result
}
```
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
}
```
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
}
```
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
}
```
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 largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 1 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 1 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 0
}
```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 {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 0
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n - 1
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n - 1
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n - 1
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return divisor
}
```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 {
var divisor = n - 1
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
var divisor = n
while divisor > 1 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```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 {
var divisor = n
while divisor > 1 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
// XCTAssertTrue failed
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
result.append(divisor)
number /= divisor
} else {
divisor += 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 number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
result.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return result
}
```
func factorize(n: Int) -> [Int] {
var result: [Int] = []
var num = n
var i = 2
while num > 1 {
while num % i == 0 {
result.append(i)
num /= 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 num = n
var i = 2
while num > 1 {
while num % i == 0 {
result.append(i)
num /= i
}
i += 1
}
return result
}
```
func factorize(n: Int) -> [Int] {
var result: [Int] = []
var num = n
for i in 2...num {
while num % i == 0 {
result.append(i)
num /= i
}
}
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 num = n
for i in 2...num {
while num % i == 0 {
result.append(i)
num /= i
}
}
return result
}
```
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var i = 2
while number > 1 {
while number % i == 0 {
result.append(i)
number /= 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 number = n
var i = 2
while number > 1 {
while number % i == 0 {
result.append(i)
number /= i
}
i += 1
}
return result
}
```
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
result.append(divisor)
number /= divisor
}
divisor += 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 number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
result.append(divisor)
number /= divisor
}
divisor += 1
}
return result
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
factors.append(divisor)
number /= divisor
}
divisor += 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 number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
factors.append(divisor)
number /= divisor
}
divisor += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while number > 1 {
while number % i == 0 {
factors.append(i)
number /= 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 number = n
var i = 2
while number > 1 {
while number % i == 0 {
factors.append(i)
number /= i
}
i += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
result.append(divisor)
number /= divisor
} else {
divisor += 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 number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
result.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return result
}
```
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
result.append(divisor)
number /= divisor
} else {
divisor += 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 number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
result.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return result
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
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 n = n
var i = 2
while n > 1 {
while n % i == 0 {
factors.append(i)
n /= i
}
i += 1
}
return factors
}
```
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(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 = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(number)
}
}
return result
}
```
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for number in numbers {
if set.contains(number) {
continue
}
result.append(number)
set.insert(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 set = Set<Int>()
for number in numbers {
if set.contains(number) {
continue
}
result.append(number)
set.insert(number)
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(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 = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(number)
}
}
return result
}
```
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(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 = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(number)
}
}
return result
}
```
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(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 = Set<Int>()
for number in numbers {
if!seen.contains(number) {
result.append(number)
seen.insert(number)
}
}
return result
}
```
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isUppercase {
result += char.lowercased()
} else {
result += char.uppercased()
}
}
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.isUppercase {
result += char.lowercased()
} else {
result += char.uppercased()
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += char.uppercased()
} else {
result += char.lowercased()
}
}
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.isLowercase {
result += char.uppercased()
} else {
result += char.lowercased()
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
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.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += char.uppercased()
} else {
result += char.lowercased()
}
}
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.isLowercase {
result += char.uppercased()
} else {
result += char.lowercased()
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
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.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isUppercase {
result += char.lowercased()
} else {
result += char.uppercased()
}
}
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.isUppercase {
result += char.lowercased()
} else {
result += char.uppercased()
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
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.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
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.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
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.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isUppercase {
result.append(char.lowercased())
} else {
result.append(char.uppercased())
}
}
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.isUppercase {
result.append(char.lowercased())
} else {
result.append(char.uppercased())
}
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result: [String] = []
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```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] {
var result: [String] = []
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result: [String] = []
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```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] {
var result: [String] = []
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```
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) }
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { (string) -> Bool in
return string.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 { (string) -> Bool in
return string.hasPrefix(prefix)
}
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```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] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```
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) }
}
```
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) }
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```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] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```
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) }
}
// 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) }
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var filteredStrings = [String]()
for string in strings {
if string.hasPrefix(prefix) {
filteredStrings.append(string)
}
}
return filteredStrings
}
```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] {
var filteredStrings = [String]()
for string in strings {
if string.hasPrefix(prefix) {
filteredStrings.append(string)
}
}
return filteredStrings
}
```
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 }
}
```
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 }
}
```
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 }
}
```
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
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] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
func isPrime(n: Int) -> Bool {
guard n > 1 else { return false }
guard n!= 2 else { return true }
guard n % 2!= 0 else { return false }
for i in stride(from: 3, through: Int(sqrt(Double(n))), by: 2) {
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 {
guard n > 1 else { return false }
guard n!= 2 else { return true }
guard n % 2!= 0 else { return false }
for i in stride(from: 3, through: Int(sqrt(Double(n))), by: 2) {
if n % i == 0 {
return false
}
}
return true
}
```
guard n!= 2 else { return true } // '=' must have consistent whitespace on both sides
guard n!= 2 else { return true } // use of '=' in a boolean context, did you mean '=='?
guard n!= 2 else { return true } // cannot force unwrap value of non-optional type 'Int'
guard n % 2!= 0 else { return false } // expression is not assignable: binary operator returns immutable value
guard n % 2!= 0 else { return false } // use of '=' in a boolean context, did you mean '=='?
guard n % 2!= 0 else { return false } // cannot force unwrap value of non-optional type 'Int'
guard n % 2!= 0 else { return false } // '=' must have consistent whitespace on both sides
func isPrime(n: Int) -> Bool {
guard n > 1 else { return false }
guard n > 3 else { return true }
guard n % 2!= 0 else { return false }
guard n % 3!= 0 else { return false }
var i = 5
while i * i <= n {
if n % i == 0 { return false }
if n % (i + 2) == 0 { return false }
i += 6
}
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 {
guard n > 1 else { return false }
guard n > 3 else { return true }
guard n % 2!= 0 else { return false }
guard n % 3!= 0 else { return false }
var i = 5
while i * i <= n {
if n % i == 0 { return false }
if n % (i + 2) == 0 { return false }
i += 6
}
return true
}
```
guard n % 2!= 0 else { return false } // expression is not assignable: binary operator returns immutable value
guard n % 2!= 0 else { return false } // use of '=' in a boolean context, did you mean '=='?
guard n % 2!= 0 else { return false } // cannot force unwrap value of non-optional type 'Int'
guard n % 2!= 0 else { return false } // '=' must have consistent whitespace on both sides
guard n % 3!= 0 else { return false } // cannot force unwrap value of non-optional type 'Int'
guard n % 3!= 0 else { return false } // '=' must have consistent whitespace on both sides
guard n % 3!= 0 else { return false } // expression is not assignable: binary operator returns immutable value
guard n % 3!= 0 else { return false } // use of '=' in a boolean context, did you mean '=='?
func isPrime(n: Int) -> Bool {
if n <= 1 { return false }
if n <= 3 { return true }
if n % 2 == 0 { return false }
if n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 { return false }
if n % (i + 2) == 0 { return false }
i += 6
}
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 }
if n <= 3 { return true }
if n % 2 == 0 { return false }
if n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 { return false }
if n % (i + 2) == 0 { return false }
i += 6
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(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...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
guard n > 1 else { 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 {
guard n > 1 else { 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
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
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
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func isPrime(n: Int) -> Bool {
guard n > 1 else { 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 {
guard n > 1 else { return false }
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
guard n > 1 else { 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 {
guard n > 1 else { 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...Int(sqrt(Double(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...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 { return false }
if n <= 3 { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
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 }
if n <= 3 { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l[i] = l[i].sorted()
}
}
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].sorted()
}
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```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 lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = lPrime[i].sorted() // value of type 'Int' has no member 'sorted'
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l[i] = l[i].sorted()
}
}
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].sorted()
}
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
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
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i].sorted()
}
}
return lPrime
}
```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 lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortThird(l: [Int]) -> [Int] {
var lPrime = [Int]()
for i in 0..<l.count {
if i % 3!= 0 {
lPrime.append(l[i])
} else {
lPrime.append(l[i].sorted())
}
}
return lPrime
}
```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 lPrime = [Int]()
for i in 0..<l.count {
if i % 3!= 0 {
lPrime.append(l[i])
} else {
lPrime.append(l[i].sorted())
}
}
return lPrime
}
```
if i % 3!= 0 { // '=' must have consistent whitespace on both sides
if i % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 3!= 0 { // expression is not assignable: binary operator returns immutable value
lPrime.append(l[i].sorted()) // value of type 'Int' has no member 'sorted'
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
lPrime.append(l[i])
} else {
lPrime.append(l[i])
lPrime.sort()
}
}
return lPrime
}
```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
var lPrime = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
lPrime.append(l[i])
} else {
lPrime.append(l[i])
lPrime.sort()
}
}
return lPrime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 3 == 0 {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```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 lPrime = l
for i in 0..<lPrime.count {
if i % 3 == 0 {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = lPrime[i].sorted() // value of type 'Int' has no member 'sorted'
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
lPrime.append(l[i])
} else {
lPrime.append(l[i])
lPrime.sort()
}
}
return lPrime
}
```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
var lPrime = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
lPrime.append(l[i])
} else {
lPrime.append(l[i])
lPrime.sort()
}
}
return lPrime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l[i] = l[i].sorted()
}
}
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].sorted()
}
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
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
}
```
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
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 unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[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 1..<l.count {
if l[i] > max {
max = l[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 fizzBuzz(n: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// 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 fizzBuzz(n: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// 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 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 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 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 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 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 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 stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
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 stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
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 stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
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 stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
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 stride(from: 0, to: l.count, by: 2) {
l[i] = l[i].sorted()
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i].sorted()
}
}
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].sorted()
}
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in stride(from: 1, to: l.count, by: 2) {
lPrime[i] = l[i].sorted()
}
return lPrime
}
```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 lPrime = l
for i in stride(from: 1, to: l.count, by: 2) {
lPrime[i] = l[i].sorted()
}
return lPrime
}
```
lPrime[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i].sorted()
}
}
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].sorted()
}
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i].sorted()
}
}
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].sorted()
}
}
return l
}
```
l[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in stride(from: 0, to: l.count, by: 2) {
lPrime[i] = l[i]
}
for i in stride(from: 1, to: l.count, by: 2) {
lPrime[i] = l[i].sorted()
}
return lPrime
}
```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 lPrime = l
for i in stride(from: 0, to: l.count, by: 2) {
lPrime[i] = l[i]
}
for i in stride(from: 1, to: l.count, by: 2) {
lPrime[i] = l[i].sorted()
}
return lPrime
}
```
lPrime[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
let j = i + 1
if j < l.count {
l.swapAt(i, 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 stride(from: 0, to: l.count, by: 2) {
let j = i + 1
if j < l.count {
l.swapAt(i, j)
}
}
return l
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[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 = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[n - 1]
}
```
if isPrime(next) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 0
var i = 1
while i < n {
c = a + b
if isPrime(c) {
a = b
b = c
i += 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 = 0
var i = 1
while i < n {
c = a + b
if isPrime(c) {
a = b
b = c
i += 1
}
}
return c
}
```
if isPrime(c) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[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 = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[n - 1]
}
```
if isPrime(next) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [Int]()
var i = 0
var j = 1
var k = 0
while fib.count < n {
k = i + j
i = j
j = k
if isPrime(n: k) {
fib.append(k)
}
}
return fib[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 i = 0
var j = 1
var k = 0
while fib.count < n {
k = i + j
i = j
j = k
if isPrime(n: k) {
fib.append(k)
}
}
return fib[n-1]
}
```
if isPrime(n: k) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var a = 1, b = 1
var i = 1
while i < n {
let c = a + b
if isPrime(c) {
a = b
b = c
i += 1
}
}
return b
}
```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, b = 1
var i = 1
while i < n {
let c = a + b
if isPrime(c) {
a = b
b = c
i += 1
}
}
return b
}
```
if isPrime(c) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[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 = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[n - 1]
}
```
if isPrime(next) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [2, 3]
var i = 2
while fib.count < n {
let next = fib[i-1] + fib[i-2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[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 = [2, 3]
var i = 2
while fib.count < n {
let next = fib[i-1] + fib[i-2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[n-1]
}
```
if isPrime(next) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i-1] + fib[i-2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[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 = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i-1] + fib[i-2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[n-1]
}
```
if isPrime(next) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[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 = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
if isPrime(next) {
fib.append(next)
}
i += 1
}
return fib[n - 1]
}
```
if isPrime(next) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
fib.append(next)
i += 1
}
return fib[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 = [1, 2]
var i = 2
while fib.count < n {
let next = fib[i - 1] + fib[i - 2]
fib.append(next)
i += 1
}
return fib[n - 1]
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Write 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 {
// TODO: Write your code here
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
set.insert(i)
}
for i in l {
for j in l {
if set.contains(-i-j) {
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 {
var set = Set<Int>()
for i in l {
set.insert(i)
}
for i in l {
for j in l {
if set.contains(-i-j) {
return true
}
}
}
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
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 {
set.insert(l[i])
set.insert(l[j])
set.insert(l[k])
}
}
}
}
return set.count == 3
}
```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 set = Set<Int>()
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 {
set.insert(l[i])
set.insert(l[j])
set.insert(l[k])
}
}
}
}
return set.count == 3
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
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 {
var set = Set<Int>()
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
}
```
var set = Set<Int>() // initialization of variable 'set' was never used; consider replacing with assignment to '_' or removing it
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Implement this function
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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
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 {
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 {
var set = Set<Int>()
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 {
set.insert(l[i])
set.insert(l[j])
set.insert(l[k])
}
}
}
}
return set.count == 3
}
```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 set = Set<Int>()
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 {
set.insert(l[i])
set.insert(l[j])
set.insert(l[k])
}
}
}
}
return set.count == 3
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Implement this function.
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 {
// TODO: Implement this function.
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
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 {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
return false
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
// TODO: Write your code here.
}
```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 {
// TODO: Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: Write your code here.
}
```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 {
// TODO: Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
}
```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 {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
}
```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 {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
}
```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 {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: Write your code here.
}
```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 {
// TODO: Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(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 = [Int]()
for i in l {
result.append(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] {
var result = [Int]()
for i in l {
result.append(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 = [Int]()
for i in l {
result.append(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] {
var result = [Int]()
for i in l {
result.append(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 = [Int]()
for i in l {
result.append(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] {
var result = [Int]()
for i in 0..<l.count {
result.append(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 = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var newList = [Int]()
for i in l {
newList.append(i + 1)
}
return newList
}
```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 newList = [Int]()
for i in l {
newList.append(i + 1)
}
return newList
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(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 = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(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 = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Bool'
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
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 i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
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 i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
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 set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
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 i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
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 set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
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 set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
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 set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
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 i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
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 i in l {
if seen.contains(-i) {
return true
}
seen.insert(i)
}
return false
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
let remainder = num % base
result = "\(remainder)" + result
num /= 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 num = x
while num > 0 {
let remainder = num % base
result = "\(remainder)" + result
num /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
result = String(num % base) + result
num /= 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 num = x
while num > 0 {
result = String(num % base) + result
num /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = "\(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 = "\(remainder % base)" + result
remainder /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
result = "\(num % base)" + result
num /= 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 num = x
while num > 0 {
result = "\(num % base)" + result
num /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = "\(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 = "\(remainder % base)" + result
remainder /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
result = "\(num % base)" + result
num /= 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 num = x
while num > 0 {
result = "\(num % base)" + result
num /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
result = String(num % base) + result
num /= 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 num = x
while num > 0 {
result = String(num % base) + result
num /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = "\(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 = "\(remainder % base)" + result
remainder /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = "\(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 = "\(remainder % base)" + result
remainder /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = "\(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 = "\(remainder % base)" + result
remainder /= base
}
return result
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(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 Double(a * h) / 2
}
```
func fib4(n: Int) -> Int {
// TODO: Write your code here
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 {
// TODO: Write your code here
return 0
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func fib4(n: Int) -> Int {
// TODO: Write your code here
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 {
// TODO: Write your code here
return 0
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
var i = 0
while i < n {
let temp = a + b + c + d
a = b
b = c
c = d
d = temp
i += 1
}
return a
}
```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 a = 0
var b = 0
var c = 2
var d = 0
var i = 0
while i < n {
let temp = a + b + c + d
a = b
b = c
c = d
d = temp
i += 1
}
return a
}
```
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```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 a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
// Write your code here.
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for i in 4...n {
d = a + b + c + d
a = b
b = c
c = d
}
return d
}
```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 {
// Write your code here.
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for i in 4...n {
d = a + b + c + d
a = b
b = c
c = d
}
return d
}
```
for i in 4...n { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
d = a + b + c
a = b
b = c
c = d
}
return d
}
```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 a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
d = a + b + c
a = b
b = c
c = d
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
// TODO: Write your code here
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 {
// TODO: Write your code here
return 0
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
// TODO: Write your code here
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 {
// TODO: Write your code here
return 0
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```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 a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
} else {
return Double(sorted[mid])
}
}
```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 mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
} else {
return Double(sorted[mid])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let mid = count / 2
if count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[mid])
}
}
```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 count = sorted.count
let mid = count / 2
if count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[mid])
}
}
```
func median(l: [Int]) -> Double {
// TODO: implement
}
```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 {
// TODO: implement
}
```
} // missing return in global function expected to return 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[middle] + sorted[middle - 1]) / 2.0
} else {
return Double(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 Double(sorted[middle] + sorted[middle - 1]) / 2.0
} else {
return Double(sorted[middle])
}
}
```
func median(l: [Int]) -> Double {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[mid])
}
}
```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 mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[mid])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
} else {
return Double(sorted[mid])
}
}
```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 mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
} else {
return Double(sorted[mid])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
let index = count / 2
return Double(sorted[index - 1] + sorted[index]) / 2
} else {
let index = (count + 1) / 2
return Double(sorted[index - 1])
}
}
```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 count = sorted.count
if count % 2 == 0 {
let index = count / 2
return Double(sorted[index - 1] + sorted[index]) / 2
} else {
let index = (count + 1) / 2
return Double(sorted[index - 1])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
} else {
return Double(sorted[mid])
}
}
```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 mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
} else {
return Double(sorted[mid])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[mid])
}
}
```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 mid = sorted.count / 2
if sorted.count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[mid])
}
}
```
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
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 text = text.lowercased()
let reversed = String(text.reversed())
return 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 isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let characters = Array(text)
let reversedCharacters = characters.reversed()
let reversedText = String(reversedCharacters)
return text == reversedText
}
```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 text = text.lowercased()
let characters = Array(text)
let reversedCharacters = characters.reversed()
let reversedText = String(reversedCharacters)
return text == reversedText
}
```
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let characters = Array(text)
let reversedCharacters = Array(text.reversed())
return characters == reversedCharacters
}
```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 text = text.lowercased()
let characters = Array(text)
let reversedCharacters = Array(text.reversed())
return characters == reversedCharacters
}
```
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 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 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())
}
```
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())
}
```
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 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())
}
```
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```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 {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```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 {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```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 {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```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 {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n /= 2
p = (p * p) % p
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
p = (p * p) % p
n /= 2
}
return result
}
```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 {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
p = (p * p) % p
n /= 2
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
result.append(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!"aeiouAEIOU".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
result.append(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!"aeiouAEIOU".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
result.append(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!"aeiouAEIOU".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" {
result += String(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 += String(char)
}
}
return result
}
```
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // use of '=' in a boolean context, did you mean '=='?
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot assign value of type '()' to type 'Character'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiou".contains(char) {
result.append(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!"aeiou".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiou".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
result += String(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!"aeiouAEIOU".contains(char) {
result += String(char)
}
}
return result
}
```
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiou".contains(char) {
result.append(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!"aeiou".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiou".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiou".contains(char) {
result.append(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!"aeiou".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiou".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" {
result += String(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 += String(char)
}
}
return result
}
```
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // use of '=' in a boolean context, did you mean '=='?
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot assign value of type '()' to type 'Character'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" {
result += String(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 += String(char)
}
}
return result
}
```
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'String' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot convert value of type 'Character' to expected argument type 'Bool'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // use of '=' in a boolean context, did you mean '=='?
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // '=' must have consistent whitespace on both sides
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot force unwrap value of non-optional type 'Character'
if char!= "a" && char!= "e" && char!= "i" && char!= "o" && char!= "u" { // cannot assign value of type '()' to type 'Character'
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
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for n in l {
if n >= 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 n in l {
if n >= t {
return false
}
}
return true
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
var result = true
for i in l {
if i >= t {
result = false
}
}
return result
}
```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 {
var result = true
for i in l {
if i >= t {
result = false
}
}
return result
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
for n in l {
if n >= 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 n in l {
if n >= t {
return false
}
}
return true
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
for n in l {
if n >= 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 n in l {
if n >= t {
return false
}
}
return true
}
```
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
}
```
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
}
```
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
}
```
// XCTAssertTrue failed
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
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
for n in l {
if n >= 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 n in l {
if n >= t {
return false
}
}
return true
}
```
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func remainder(x: Int, y: Int) -> Int {
return x % y
}
func squareRoot(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
func square(x: Int) -> Int {
return x * x
}
func cube(x: Int) -> Int {
return x * x * x
}
func average(x: Int, y: Int) -> Double {
return Double(x + y) / 2
}
func absoluteValue(x: Int) -> Int {
return abs(x)
}
func max(x: Int, y: Int) -> Int {
return max(x, y)
}
func min(x: Int, y: Int) -> Int {
return min(x, y)
}
func numberOfDigits(x: Int) -> Int {
return String(x).characters.count
}
func numberOfDigits(x: Double) -> Int {
return String(x).characters.count
}
func numberOfDigits(x: Float) -> Int {
return String(x).characters.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
}
// Subtract two numbers x and y
// subtract(x: 2, y: 3) == -1
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Return the remainder of two numbers x and y
// remainder(x: 2, y: 3) == 2
// remainder(x: 5, y: 7) == 5
func remainder(x: Int, y: Int) -> Int {
return x % y
}
// Return the square root of a number x
// squareRoot(x: 4) == 2
// squareRoot(x: 9) == 3
func squareRoot(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
// Return the square of a number x
// square(x: 2) == 4
// square(x: 3) == 9
func square(x: Int) -> Int {
return x * x
}
// Return the cube of a number x
// cube(x: 2) == 8
// cube(x: 3) == 27
func cube(x: Int) -> Int {
return x * x * x
}
// Return the average of two numbers x and y
// average(x: 2, y: 3) == 2.5
// average(x: 5, y: 7) == 6
func average(x: Int, y: Int) -> Double {
return Double(x + y) / 2
}
// Return the absolute value of a number x
// absoluteValue(x: -2) == 2
// absoluteValue(x: 3) == 3
func absoluteValue(x: Int) -> Int {
return abs(x)
}
// Return the largest of two numbers x and y
// max(x: 2, y: 3) == 3
// max(x: 5, y: 7) == 7
func max(x: Int, y: Int) -> Int {
return max(x, y)
}
// Return the smallest of two numbers x and y
// min(x: 2, y: 3) == 2
// min(x: 5, y: 7) == 5
func min(x: Int, y: Int) -> Int {
return min(x, y)
}
// Return the number of digits of a number x
// numberOfDigits(x: 2) == 1
// numberOfDigits(x: 3) == 1
// numberOfDigits(x: 12) == 2
// numberOfDigits(x: 123) == 3
func numberOfDigits(x: Int) -> Int {
return String(x).characters.count
}
// Return the number of digits of a number x
// numberOfDigits(x: 2) == 1
// numberOfDigits(x: 3) == 1
// numberOfDigits(x: 12) == 2
// numberOfDigits(x: 123) == 3
func numberOfDigits(x: Double) -> Int {
return String(x).characters.count
}
// Return the number of digits of a number x
// numberOfDigits(x: 2) == 1
// numberOfDigits(x: 3) == 1
// numberOfDigits(x: 12) == 2
// numberOfDigits(x: 123) == 3
func numberOfDigits(x: Float) -> Int {
return String(x).characters.count
}
// Return the number of digits of a number x
// numberOfDigits(x: 2) == 1
// numberOfDigits(x: 3) == 1
return String(x).characters.count // 'characters' is unavailable: Please use String directly
return String(x).characters.count // 'characters' is unavailable: Please use String directly
return String(x).characters.count // 'characters' is unavailable: Please use String directly
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
}
```
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(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
}
// Subtract two numbers x and y
// subtract(x: 2, y: 3) == -1
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
```
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
}
```
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func remainder(x: Int, y: Int) -> Int {
return x % y
}
func average(x: Int, y: Int) -> Double {
return Double(x + y) / 2
}
func average(x: Int, y: Int, z: Int) -> Double {
return Double(x + y + z) / 3
}
func average(x: Int, y: Int, z: Int, w: Int) -> Double {
return Double(x + y + z + w) / 4
}
func average(x: Int, y: Int, z: Int, w: Int, v: Int) -> Double {
return Double(x + y + z + w + v) / 5
}
```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
}
// Subtract two numbers x and y
// subtract(x: 2, y: 3) == -1
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Calculate the remainder of two numbers x and y
// remainder(x: 2, y: 3) == 2
// remainder(x: 5, y: 7) == 5
func remainder(x: Int, y: Int) -> Int {
return x % y
}
// Calculate the average of two numbers x and y
// average(x: 2, y: 3) == 2.5
// average(x: 5, y: 7) == 6
func average(x: Int, y: Int) -> Double {
return Double(x + y) / 2
}
// Calculate the average of three numbers x, y, and z
// average(x: 2, y: 3, z: 4) == 3
// average(x: 5, y: 7, z: 9) == 7
func average(x: Int, y: Int, z: Int) -> Double {
return Double(x + y + z) / 3
}
// Calculate the average of four numbers x, y, z, and w
// average(x: 2, y: 3, z: 4, w: 5) == 3.5
// average(x: 5, y: 7, z: 9, w: 11) == 8.5
func average(x: Int, y: Int, z: Int, w: Int) -> Double {
return Double(x + y + z + w) / 4
}
// Calculate the average of five numbers x, y, z, w, and v
// average(x: 2, y: 3, z: 4, w: 5, v: 6) == 4
// average(x: 5, y: 7, z: 9, w: 11, v: 13) == 9
func average(x: Int, y: Int, z: Int, w: Int, v: Int) -> Double {
return Double(x + y + z + w + v) / 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
}
```
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
}
```
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func add(x: Double, y: Double) -> Double {
return x + y
}
func subtract(x: Double, y: Double) -> Double {
return x - y
}
func multiply(x: Double, y: Double) -> Double {
return x * y
}
func divide(x: Double, y: Double) -> Double {
return x / y
}
func add(x: Float, y: Float) -> Float {
return x + y
}
func subtract(x: Float, y: Float) -> Float {
return x - y
}
func multiply(x: Float, y: Float) -> Float {
return x * y
}
func divide(x: Float, y: Float) -> Float {
return x / y
}
func add(x: CGFloat, y: CGFloat) -> CGFloat {
return x + y
}
func subtract(x: CGFloat, y: CGFloat) -> CGFloat {
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
}
// Subtract two numbers x and y
// subtract(x: 2, y: 3) == -1
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Add two numbers x and y
// add(x: 2.5, y: 3.5) == 6.0
// add(x: 5.5, y: 7.5) == 13.0
func add(x: Double, y: Double) -> Double {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 2.5, y: 3.5) == -1.0
// subtract(x: 5.5, y: 7.5) == -2.0
func subtract(x: Double, y: Double) -> Double {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2.5, y: 3.5) == 7.5
// multiply(x: 5.5, y: 7.5) == 41.25
func multiply(x: Double, y: Double) -> Double {
return x * y
}
// Divide two numbers x and y
// divide(x: 2.5, y: 3.5) == 0.7142857142857143
// divide(x: 5.5, y: 7.5) == 0.75
func divide(x: Double, y: Double) -> Double {
return x / y
}
// Add two numbers x and y
// add(x: 2.5, y: 3.5) == 6.0
// add(x: 5.5, y: 7.5) == 13.0
func add(x: Float, y: Float) -> Float {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 2.5, y: 3.5) == -1.0
// subtract(x: 5.5, y: 7.5) == -2.0
func subtract(x: Float, y: Float) -> Float {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2.5, y: 3.5) == 7.5
// multiply(x: 5.5, y: 7.5) == 41.25
func multiply(x: Float, y: Float) -> Float {
return x * y
}
// Divide two numbers x and y
// divide(x: 2.5, y: 3.5) == 0.7142857142857143
// divide(x: 5.5, y: 7.5) == 0.75
func divide(x: Float, y: Float) -> Float {
return x / y
}
// Add two numbers x and y
// add(x: 2.5, y: 3.5) == 6.0
// add(x: 5.5, y: 7.5) == 13.0
func add(x: CGFloat, y: CGFloat) -> CGFloat {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 2.5, y: 3.5) == -1.0
// subtract(x: 5.5, y: 7.5) == -2.0
func subtract(x: CGFloat, y: CGFloat) -> CGFloat {
return x - y
}
//
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(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
}
// Subtract two numbers x and y
// subtract(x: 2, y: 3) == -1
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
```
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
}
```
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
var result = true
while!s0.isEmpty &&!s1.isEmpty {
if s0.first!!= s1.first! {
result = false
break
}
s0.removeFirst()
s1.removeFirst()
}
return result
}
```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 result = true
while!s0.isEmpty &&!s1.isEmpty {
if s0.first!!= s1.first! {
result = false
break
}
s0.removeFirst()
s1.removeFirst()
}
return result
}
```
while!s0.isEmpty &&!s1.isEmpty { // expected expression, var, or let in 'while' condition
if s0.first!!= s1.first! { // '=' must have consistent whitespace on both sides
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
while!s0.isEmpty &&!s1.isEmpty {
if s0.removeFirst()!= s1.removeFirst() {
return false
}
}
return s0.isEmpty && s1.isEmpty
}
```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
while!s0.isEmpty &&!s1.isEmpty {
if s0.removeFirst()!= s1.removeFirst() {
return false
}
}
return s0.isEmpty && s1.isEmpty
}
```
while!s0.isEmpty &&!s1.isEmpty { // expected expression, var, or let in 'while' condition
if s0.removeFirst()!= s1.removeFirst() { // '=' must have consistent whitespace on both sides
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
if let count = dict[char] {
if count == 0 {
return false
} else {
dict[char] = count - 1
}
} else {
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 {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
if let count = dict[char] {
if count == 0 {
return false
} else {
dict[char] = count - 1
}
} else {
return false
}
}
return true
}
```
dict[char] = (dict[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) + 1 // expected ',' separator
func sameChars(s0: String, s1: String) -> Bool {
var s0Chars = [Character: Int]()
var s1Chars = [Character: Int]()
for char in s0 {
s0Chars[char] = (s0Chars[char]?? 0) + 1
}
for char in s1 {
s1Chars[char] = (s1Chars[char]?? 0) + 1
}
return s0Chars == s1Chars
}
```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 s0Chars = [Character: Int]()
var s1Chars = [Character: Int]()
for char in s0 {
s0Chars[char] = (s0Chars[char]?? 0) + 1
}
for char in s1 {
s1Chars[char] = (s1Chars[char]?? 0) + 1
}
return s0Chars == s1Chars
}
```
s0Chars[char] = (s0Chars[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
s0Chars[char] = (s0Chars[char]?? 0) + 1 // expected ',' separator
s0Chars[char] = (s0Chars[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
s1Chars[char] = (s1Chars[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
s1Chars[char] = (s1Chars[char]?? 0) + 1 // expected ',' separator
s1Chars[char] = (s1Chars[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
let s0Chars = s0.characters.map { String($0) }
let s1Chars = s1.characters.map { String($0) }
for char in s0Chars {
if let index = s1Chars.index(of: char) {
s1Chars.remove(at: index)
} else {
return false
}
}
return s1Chars.count == 0
}
```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
let s0Chars = s0.characters.map { String($0) }
let s1Chars = s1.characters.map { String($0) }
for char in s0Chars {
if let index = s1Chars.index(of: char) {
s1Chars.remove(at: index)
} else {
return false
}
}
return s1Chars.count == 0
}
```
let s0Chars = s0.characters.map { String($0) } // 'characters' is unavailable: Please use String directly
let s1Chars = s1.characters.map { String($0) } // 'characters' is unavailable: Please use String directly
if let index = s1Chars.index(of: char) { // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
s1Chars.remove(at: index) // cannot use mutating member on immutable value: 's1Chars' is a 'let' constant
func sameChars(s0: String, s1: String) -> Bool {
var dict0 = [Character: Int]()
var dict1 = [Character: Int]()
for char in s0 {
dict0[char] = (dict0[char]?? 0) + 1
}
for char in s1 {
dict1[char] = (dict1[char]?? 0) + 1
}
return dict0 == dict1
}
```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 dict0 = [Character: Int]()
var dict1 = [Character: Int]()
for char in s0 {
dict0[char] = (dict0[char]?? 0) + 1
}
for char in s1 {
dict1[char] = (dict1[char]?? 0) + 1
}
return dict0 == dict1
}
```
dict0[char] = (dict0[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict0[char] = (dict0[char]?? 0) + 1 // expected ',' separator
dict0[char] = (dict0[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict1[char] = (dict1[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict1[char] = (dict1[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict1[char] = (dict1[char]?? 0) + 1 // expected ',' separator
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```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.sorted() == s1.sorted()
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
return Set(s0).isSubset(of: Set(s1))
}
```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 Set(s0).isSubset(of: Set(s1))
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = s0.map { String($0) }
let s1Chars = s1.map { String($0) }
return s0Chars.sorted() == s1Chars.sorted()
}
```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 {
let s0Chars = s0.map { String($0) }
let s1Chars = s1.map { String($0) }
return s0Chars.sorted() == s1Chars.sorted()
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
var s0Chars = [Character]()
var s1Chars = [Character]()
for char in s0 {
s0Chars.append(char)
}
for char in s1 {
s1Chars.append(char)
}
s0Chars.sort()
s1Chars.sort()
return s0Chars == s1Chars
}
```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 s0Chars = [Character]()
var s1Chars = [Character]()
for char in s0 {
s0Chars.append(char)
}
for char in s1 {
s1Chars.append(char)
}
s0Chars.sort()
s1Chars.sort()
return s0Chars == s1Chars
}
```
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
// XCTAssertTrue failed
func fib(n: Int) -> Int {
if n <= 1 {
return n
}
return fib(n: n - 1) + fib(n: 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 n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 0 {
return 0
} else {
return fib(n: n - 1) + fib(n: 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 == 0 {
return 0
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```
func fib(n: Int) -> Int {
if n <= 1 {
return n
}
return fib(n: n - 1) + fib(n: 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 n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: 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
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: 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: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n <= 1 {
return n
}
return fib(n: n - 1) + fib(n: 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 n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n <= 1 {
return n
}
return fib(n: n - 1) + fib(n: 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 n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 0 {
return 0
} else {
return fib(n: n - 1) + fib(n: 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 == 0 {
return 0
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```
func fib(n: Int) -> Int {
if n <= 1 {
return n
}
return fib(n: n - 1) + fib(n: 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 n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: 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: n - 1) + fib(n: n - 2)
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
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 char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = true
var isIncreasing = true
var prev = l[0]
for i in 1..<l.count {
if l[i] < prev {
isDecreasing = false
}
if l[i] > prev {
isIncreasing = false
}
if!isDecreasing &&!isIncreasing {
isMonotonic = false
}
prev = l[i]
}
return isMonotonic
}
```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 isMonotonic = true
var isDecreasing = true
var isIncreasing = true
var prev = l[0]
for i in 1..<l.count {
if l[i] < prev {
isDecreasing = false
}
if l[i] > prev {
isIncreasing = false
}
if!isDecreasing &&!isIncreasing {
isMonotonic = false
}
prev = l[i]
}
return isMonotonic
}
```
if!isDecreasing &&!isIncreasing { // expected expression, var, or let in 'if' condition
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let isAscending = l.reduce(true) { $0 && $1 <= $2 }
let isDescending = l.reduce(true) { $0 && $1 >= $2 }
return isAscending || isDescending
}
```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 {
guard l.count > 1 else { return true }
let isAscending = l.reduce(true) { $0 && $1 <= $2 }
let isDescending = l.reduce(true) { $0 && $1 >= $2 }
return isAscending || isDescending
}
```
let isAscending = l.reduce(true) { $0 && $1 <= $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
let isDescending = l.reduce(true) { $0 && $1 >= $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let isAscending = l.reduce(true) { $0 && $1 <= $2 }
let isDescending = l.reduce(true) { $0 && $1 >= $2 }
return isAscending || isDescending
}
```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 {
guard l.count > 1 else { return true }
let isAscending = l.reduce(true) { $0 && $1 <= $2 }
let isDescending = l.reduce(true) { $0 && $1 >= $2 }
return isAscending || isDescending
}
```
let isAscending = l.reduce(true) { $0 && $1 <= $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
let isDescending = l.reduce(true) { $0 && $1 >= $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let isAscending = l.reduce(true) { $0 && $1 <= $2 }
let isDescending = l.reduce(true) { $0 && $1 >= $2 }
return isAscending || isDescending
}
```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 {
guard l.count > 1 else { return true }
let isAscending = l.reduce(true) { $0 && $1 <= $2 }
let isDescending = l.reduce(true) { $0 && $1 >= $2 }
return isAscending || isDescending
}
```
let isAscending = l.reduce(true) { $0 && $1 <= $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
let isDescending = l.reduce(true) { $0 && $1 >= $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let first = l[0]
let last = l[l.count - 1]
let isAscending = first < last
let isDescending = first > last
if isAscending || isDescending {
for i in 1..<l.count {
let current = l[i]
let previous = l[i - 1]
if isAscending {
if current < previous {
return false
}
} else {
if current > previous {
return false
}
}
}
}
return true
}
```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 {
guard l.count > 1 else { return true }
let first = l[0]
let last = l[l.count - 1]
let isAscending = first < last
let isDescending = first > last
if isAscending || isDescending {
for i in 1..<l.count {
let current = l[i]
let previous = l[i - 1]
if isAscending {
if current < previous {
return false
}
} else {
if current > previous {
return false
}
}
}
}
return true
}
```
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = true
var isIncreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isDecreasing = false
} else if l[i] < l[i - 1] {
isIncreasing = false
}
}
isMonotonic = isDecreasing || isIncreasing
return isMonotonic
}
```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 isMonotonic = true
var isDecreasing = true
var isIncreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isDecreasing = false
} else if l[i] < l[i - 1] {
isIncreasing = false
}
}
isMonotonic = isDecreasing || isIncreasing
return isMonotonic
}
```
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isMonotonic = true
var isAscending = true
for i in 1..<l.count {
if l[i] < l[i - 1] {
isAscending = false
}
if l[i] > l[i - 1] {
isMonotonic = false
}
}
return isMonotonic && isAscending
}
```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 {
guard l.count > 1 else { return true }
var isMonotonic = true
var isAscending = true
for i in 1..<l.count {
if l[i] < l[i - 1] {
isAscending = false
}
if l[i] > l[i - 1] {
isMonotonic = false
}
}
return isMonotonic && isAscending
}
```
// XCTAssertTrue failed
```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 {
guard l.count > 1 else { return true }
let first = l[0]
let second = l[1]
let isFirstBigger = first > second
let isFirstSmaller = first < second
let isFirstEqual = first == second
let isSecondBigger = second > first
let isSecondSmaller = second < first
let isSecondEqual = second == first
let isFirstBiggerOrEqual = first >= second
let isFirstSmallerOrEqual = first <= second
let isSecondBiggerOrEqual = second >= first
let isSecondSmallerOrEqual = second <= first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmallerSecond = first < second
let isSecondBiggerFirst = second > first
let isSecondSmallerFirst = second < first
let isFirstBiggerOrEqualSecond = first >= second
let isFirstSmallerOrEqualSecond = first <= second
let isSecondBiggerOrEqualFirst = second >= first
let isSecondSmallerOrEqualFirst = second <= first
let isFirstBiggerSecond = first > second
let isFirstSmaller
XCTAssertTrue(monotonic(l: [1, 2, 4, 10]) == true) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [1, 2, 4, 20]) == true) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [1, 20, 4, 10]) == false) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [4, 1, 0, -10]) == true) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [4, 1, 1, 0]) == true) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [1, 2, 3, 2, 5, 60]) == false) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [1, 2, 3, 4, 5, 60]) == true) // cannot find 'monotonic' in scope
XCTAssertTrue(monotonic(l: [9, 9, 9, 9]) == true) // cannot find 'monotonic' in scope
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = true
var isIncreasing = true
var previousValue = l[0]
for i in 1..<l.count {
if l[i] > previousValue {
isDecreasing = false
} else if l[i] < previousValue {
isIncreasing = false
}
previousValue = l[i]
}
isMonotonic = isDecreasing || isIncreasing
return isMonotonic
}
```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 isMonotonic = true
var isDecreasing = true
var isIncreasing = true
var previousValue = l[0]
for i in 1..<l.count {
if l[i] > previousValue {
isDecreasing = false
} else if l[i] < previousValue {
isIncreasing = false
}
previousValue = l[i]
}
isMonotonic = isDecreasing || isIncreasing
return isMonotonic
}
```
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let first = l[0]
let last = l[l.count - 1]
let isFirstBigger = first > last
let isLastBigger = last > first
var isMonotonic = true
for i in 1..<l.count {
if isFirstBigger {
if l[i] < l[i - 1] {
isMonotonic = false
break
}
} else {
if l[i] > l[i - 1] {
isMonotonic = false
break
}
}
}
return isMonotonic
}
```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 {
guard l.count > 1 else { return true }
let first = l[0]
let last = l[l.count - 1]
let isFirstBigger = first > last
let isLastBigger = last > first
var isMonotonic = true
for i in 1..<l.count {
if isFirstBigger {
if l[i] < l[i - 1] {
isMonotonic = false
break
}
} else {
if l[i] > l[i - 1] {
isMonotonic = false
break
}
}
}
return isMonotonic
}
```
let isLastBigger = last > first // initialization of immutable value 'isLastBigger' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for element in l1 {
if l2.contains(element) &&!result.contains(element) {
result.append(element)
}
}
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]()
for element in l1 {
if l2.contains(element) &&!result.contains(element) {
result.append(element)
}
}
return result
}
```
if l2.contains(element) &&!result.contains(element) { // expected '{' after 'if' condition
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for item in l1 {
if l2.contains(item) {
result.append(item)
}
}
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]()
for item in l1 {
if l2.contains(item) {
result.append(item)
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
for element in l1 {
if l2.contains(element) {
result.append(element)
}
}
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] = []
for element in l1 {
if l2.contains(element) {
result.append(element)
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
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 = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
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: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
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 = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
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: [Int] = []
for i in l1 {
if l2.contains(i) {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
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: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
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 = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
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: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrimeFactor = 1
var i = 2
while n > 1 {
if n % i == 0 {
n /= i
largestPrimeFactor = 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 n = n
var largestPrimeFactor = 1
var i = 2
while n > 1 {
if n % i == 0 {
n /= i
largestPrimeFactor = i
} else {
i += 1
}
}
return largestPrimeFactor
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
largestPrimeFactor = i
} else {
i += 1
}
}
return n == 1? largestPrimeFactor : 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 n = n
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
largestPrimeFactor = i
} else {
i += 1
}
}
return n == 1? largestPrimeFactor : n
}
```
return n == 1? largestPrimeFactor : n // cannot convert return expression of type 'Bool' to return type 'Int'
return n == 1? largestPrimeFactor : n // consecutive statements on a line must be separated by ';'
return n == 1? largestPrimeFactor : n // variable is unused
return n == 1? largestPrimeFactor : n // expected expression
return n == 1? largestPrimeFactor : n // cannot use optional chaining on non-optional value of type 'Int'
return n == 1? largestPrimeFactor : n // consecutive statements on a line must be separated by ';'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrimeFactor = 1
for i in 2...n {
while n % i == 0 {
largestPrimeFactor = i
n /= i
}
}
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 n = n
var largestPrimeFactor = 1
for i in 2...n {
while n % i == 0 {
largestPrimeFactor = i
n /= i
}
}
return largestPrimeFactor
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrime = 1
while n % 2 == 0 {
largestPrime = 2
n /= 2
}
var i = 3
while i * i <= n {
while n % i == 0 {
largestPrime = i
n /= i
}
i += 2
}
if n > 2 {
largestPrime = n
}
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 n = n
var largestPrime = 1
while n % 2 == 0 {
largestPrime = 2
n /= 2
}
var i = 3
while i * i <= n {
while n % i == 0 {
largestPrime = i
n /= i
}
i += 2
}
if n > 2 {
largestPrime = n
}
return largestPrime
}
```
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
while n % i == 0 {
largestPrimeFactor = i
n /= i
}
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 n = n
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
while n % i == 0 {
largestPrimeFactor = i
n /= i
}
i += 1
}
return largestPrimeFactor
}
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
while n % i == 0 {
n /= i
}
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 n = n
var i = 2
while i * i <= n {
while n % i == 0 {
n /= i
}
i += 1
}
return n
}
```
// XCTAssertTrue failed
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
}
```
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
}
```
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
}
```
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
}
```
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
}
```
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
}
```
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
}
```
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
}
```
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
}
```
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
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
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
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
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 char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
func derivative(xs: [Int]) -> [Int] {
return []
}
```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] {
return []
}
```
// 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
}
```
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] {
// TODO: Implement this function.
}
```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] {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return '[Int]'
func derivative(xs: [Int]) -> [Int] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Int]'
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - 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 {
result.append(xs[i] * (xs.count - i))
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
return []
}
```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] {
return []
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
return []
}
```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] {
return []
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<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 0..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
// 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
}
```
// 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: n - 1) + fibfib(n: n - 2) + fibfib(n: 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: n - 1) + fibfib(n: n - 2) + fibfib(n: n - 3)
}
```
func fibfib(n: Int) -> Int {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func fibfib(n: Int) -> Int {
if n < 3 {
return 0
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
let temp = a + b + c
a = b
b = c
c = temp
}
return c
}
```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 < 3 {
return 0
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
let temp = a + b + c
a = b
b = c
c = temp
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```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 <= 2 {
return 0
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 1...n {
a = b
b = c
c = a + b + c
}
return a
}
```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 {
var a = 0
var b = 0
var c = 1
for _ in 1...n {
a = b
b = c
c = a + b + c
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b + c
}
return a
}
```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 {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b + c
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b + c
}
return a
}
```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 {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b + c
}
return a
}
```
// XCTAssertTrue failed
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: n - 1) + fibfib(n: n - 2) + fibfib(n: 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: n - 1) + fibfib(n: n - 2) + fibfib(n: n - 3)
}
}
```
func fibfib(n: Int) -> Int {
guard n > 2 else { return 0 }
var a = 0
var b = 0
var c = 1
for _ in 3...n {
let d = a + b + c
a = b
b = c
c = d
}
return c
}
```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 {
guard n > 2 else { return 0 }
var a = 0
var b = 0
var c = 1
for _ in 3...n {
let d = a + b + c
a = b
b = c
c = d
}
return c
}
```
// XCTAssertTrue failed
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: n - 1) + fibfib(n: n - 2) + fibfib(n: 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: n - 1) + fibfib(n: n - 2) + fibfib(n: n - 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
}
```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 {
let vowels = "aeiou"
var count = 0
for char in s.lowercased() {
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.lowercased() {
if vowels.contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if "aeiou".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 {
var count = 0
for char in s {
if "aeiou".contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
let vowels = ["a", "e", "i", "o", "u"]
var count = 0
for char in s.lowercased() {
if vowels.contains(String(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 = ["a", "e", "i", "o", "u"]
var count = 0
for char in s.lowercased() {
if vowels.contains(String(char)) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if "aeiou".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 {
var count = 0
for char in s {
if "aeiou".contains(char) {
count += 1
}
}
return 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
default:
break
}
}
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
default:
break
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if "aeiouAEIOU".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 {
var count = 0
for char in s {
if "aeiouAEIOU".contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s.lowercased() {
if "aeiou".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 {
var count = 0
for char in s.lowercased() {
if "aeiou".contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if "aeiou".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 {
var count = 0
for char in s {
if "aeiou".contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```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.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```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.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```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.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'String'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let n = digits.count
if shift > n {
return String(digits.reversed())
}
let left = digits[0..<n-shift]
let right = digits[n-shift..<n]
return String(left + right)
}
```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.map { String($0) }
let n = digits.count
if shift > n {
return String(digits.reversed())
}
let left = digits[0..<n-shift]
let right = digits[n-shift..<n]
return String(left + right)
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
return String(digits.reversed()) // no exact matches in call to initializer
return String(left + right) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```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.map { String($0) }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.map { String($0) }.joined()
}
```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.map { Int(String($0))! }
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.map { String($0) }.joined()
}
```
let digits = String(x).characters.map { Int(String($0))! } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
let shift = shift % digits.count
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```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($0) }
let shift = shift % digits.count
let shifted = digits.dropFirst(shift) + digits.dropLast(digits.count - shift)
return shifted.joined()
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let n = digits.count
let s = shift % n
return String(digits[n-s..<n] + digits[0..<n-s])
}
```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.map { String($0) }
let n = digits.count
let s = shift % n
return String(digits[n-s..<n] + digits[0..<n-s])
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
return String(digits[n-s..<n] + digits[0..<n-s]) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
let n = digits.count
let s = shift % n
return String(digits[n-s..<n] + digits[0..<n-s])
}
```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($0) }
let n = digits.count
let s = shift % n
return String(digits[n-s..<n] + digits[0..<n-s])
}
```
return String(digits[n-s..<n] + digits[0..<n-s]) // no exact matches in call to initializer
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
```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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "Hello World") == 2
// wordCount(s: "One 22 three") == 3
// wordCount(s: "One, two, three") == 3
// wordCount(s: "One,two,three") == 3
// wordCount(s: "one two 3") == 3
// wordCount(s: "one two 3 four") == 4
// wordCount(s: "one two 3 four five") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "Hello World") == 2
// wordCount(s: "One 22 three") == 3
// wordCount(s: "One, two, three") == 3
// wordCount(s: "One,two,three") == 3
// wordCount(s: "one two 3") == 3
// wordCount(s: "one two 3 four") == 4
// wordCount(s: "one two 3 four five") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "Hello World") == 2
// wordCount(s: "One 22 three") == 3
// wordCount(s: "One, two, three") == 3
// wordCount(s: "One,two,three") == 3
// wordCount(s: "one two 3") == 3
// wordCount(s: "one two 3 four") == 4
// wordCount(s: "one two 3 four five") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "Hello World") == 2
// wordCount(s: "One 22 three") == 3
// wordCount(s: "One, two, three") == 3
// wordCount(s: "One,two,three") == 3
// wordCount(s: "one two 3") == 3
// wordCount(s: "one two 3 four") == 4
// wordCount(s: "one two 3 four five") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "Hello World") == 2
// wordCount(s: "One 22 three") == 3
// wordCount(s: "One, two, three") == 3
// wordCount(s: "One,two,three") == 3
// wordCount(s: "one two 3") == 3
// wordCount(s: "one two 3 four") == 4
// wordCount(s: "one two 3 four five") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "Hello World") == 2
// wordCount(s: "One 22 three") == 3
// wordCount
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!) - 64
}
}
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.isUppercase {
sum += Int(char.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
```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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
}
// Task
// Write a function that takes a string as input and returns the number of words in the string.
// Examples:
// wordCount(s: "") == 0
// wordCount(s: "a") == 1
// wordCount(s: "a b") == 2
// wordCount(s: "a b c") == 3
// wordCount(s: "a b c d") == 4
// wordCount(s: "a b c d e") == 5
func wordCount(s: String) -> Int {
return s.components(separatedBy: " ").count
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char >= "A" && char <= "Z" {
sum += Int(char.unicodeScalars.first!.value)
}
}
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 >= "A" && char <= "Z" {
sum += Int(char.unicodeScalars.first!.value)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!) - 64
}
}
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.isUppercase {
sum += Int(char.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(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.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ")
var apples = 0
var oranges = 0
var mango = 0
for i in arr {
if i.contains("apples") {
apples = Int(i.replacingOccurrences(of: "apples", with: ""))?? 0
}
if i.contains("oranges") {
oranges = Int(i.replacingOccurrences(of: "oranges", with: ""))?? 0
}
}
if apples + oranges > n {
return 0
}
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 arr = s.split(separator: " ")
var apples = 0
var oranges = 0
var mango = 0
for i in arr {
if i.contains("apples") {
apples = Int(i.replacingOccurrences(of: "apples", with: ""))?? 0
}
if i.contains("oranges") {
oranges = Int(i.replacingOccurrences(of: "oranges", with: ""))?? 0
}
}
if apples + oranges > n {
return 0
}
mango = n - (apples + oranges)
return mango
}
```
apples = Int(i.replacingOccurrences(of: "apples", with: ""))?? 0 // cannot use optional chaining on non-optional value of type 'Int'
apples = Int(i.replacingOccurrences(of: "apples", with: ""))?? 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
apples = Int(i.replacingOccurrences(of: "apples", with: ""))?? 0 // integer literal is unused
apples = Int(i.replacingOccurrences(of: "apples", with: ""))?? 0 // consecutive statements on a line must be separated by ';'
oranges = Int(i.replacingOccurrences(of: "oranges", with: ""))?? 0 // cannot use optional chaining on non-optional value of type 'Int'
oranges = Int(i.replacingOccurrences(of: "oranges", with: ""))?? 0 // consecutive statements on a line must be separated by ';'
oranges = Int(i.replacingOccurrences(of: "oranges", with: ""))?? 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
oranges = Int(i.replacingOccurrences(of: "oranges", with: ""))?? 0 // integer literal is unused
func fruitDistribution(s: String, n: Int) -> Int {
var apples = 0
var oranges = 0
var mangoes = 0
for i in s {
if i == "a" {
apples += 1
} else if i == "o" {
oranges += 1
} else if i == "m" {
mangoes += 1
}
}
if n < apples + oranges {
return mangoes
} else {
return mangoes + (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 {
var apples = 0
var oranges = 0
var mangoes = 0
for i in s {
if i == "a" {
apples += 1
} else if i == "o" {
oranges += 1
} else if i == "m" {
mangoes += 1
}
}
if n < apples + oranges {
return mangoes
} else {
return mangoes + (n - (apples + oranges))
}
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
var apples = 0
var oranges = 0
var mangoes = 0
var total = 0
let arr = s.components(separatedBy: " ")
for i in 0..<arr.count {
if arr[i] == "apples" {
apples = Int(arr[i-1])!
}
if arr[i] == "oranges" {
oranges = Int(arr[i-1])!
}
}
total = apples + oranges
if total > n {
mangoes = total - n
}
return mangoes
}
```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 {
var apples = 0
var oranges = 0
var mangoes = 0
var total = 0
let arr = s.components(separatedBy: " ")
for i in 0..<arr.count {
if arr[i] == "apples" {
apples = Int(arr[i-1])!
}
if arr[i] == "oranges" {
oranges = Int(arr[i-1])!
}
}
total = apples + oranges
if total > n {
mangoes = total - n
}
return mangoes
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ").map { String($0) }
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```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 fruits = s.split(separator: " ").map { String($0) }
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ").map { String($0) }
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
let mangoes = n - apples - oranges
return mangoes
}
```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 arr = s.split(separator: " ").map { String($0) }
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
let mangoes = n - apples - oranges
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
var apples = 0
var oranges = 0
var mangoes = 0
for i in s {
if i == "a" {
apples += 1
} else if i == "o" {
oranges += 1
} else if i == "m" {
mangoes += 1
}
}
if apples + oranges + mangoes > n {
return mangoes
} else {
return n - (apples + oranges + mangoes)
}
}
```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 {
var apples = 0
var oranges = 0
var mangoes = 0
for i in s {
if i == "a" {
apples += 1
} else if i == "o" {
oranges += 1
} else if i == "m" {
mangoes += 1
}
}
if apples + oranges + mangoes > n {
return mangoes
} else {
return n - (apples + oranges + mangoes)
}
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
var apples = 0
var oranges = 0
var mangoes = 0
for i in s {
if i == "a" {
apples += 1
} else if i == "o" {
oranges += 1
} else if i == "m" {
mangoes += 1
}
}
if apples + oranges + mangoes > n {
return mangoes
} else {
return n - (apples + oranges + mangoes)
}
}
```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 {
var apples = 0
var oranges = 0
var mangoes = 0
for i in s {
if i == "a" {
apples += 1
} else if i == "o" {
oranges += 1
} else if i == "m" {
mangoes += 1
}
}
if apples + oranges + mangoes > n {
return mangoes
} else {
return n - (apples + oranges + mangoes)
}
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ").map { String($0) }
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```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 fruits = s.split(separator: " ").map { String($0) }
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0].components(separatedBy: " ")[0])!
let oranges = Int(fruits[1].components(separatedBy: " ")[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 fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0].components(separatedBy: " ")[0])!
let oranges = Int(fruits[1].components(separatedBy: " ")[0])!
let mango = n - apples - oranges
return mango
}
```
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ").map { String($0) }
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```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 fruits = s.split(separator: " ").map { String($0) }
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func pluck(arr: [Int]) -> [Int] {
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return arr.count > 0? [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] {
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return arr.count > 0? [min, index] : []
}
```
return arr.count > 0? [min, index] : [] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return arr.count > 0? [min, index] : [] // expected expression
return arr.count > 0? [min, index] : [] // cannot use optional chaining on non-optional value of type 'Int'
return arr.count > 0? [min, index] : [] // consecutive statements on a line must be separated by ';'
return arr.count > 0? [min, index] : [] // cannot convert return expression of type 'Bool' to return type '[Int]'
return arr.count > 0? [min, index] : [] // value of type 'Int' has no subscripts
func pluck(arr: [Int]) -> [Int] {
let even = arr.filter { $0 % 2 == 0 }
guard!even.isEmpty else { return [] }
let min = even.min()!
let index = arr.firstIndex(of: min)!
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] {
let even = arr.filter { $0 % 2 == 0 }
guard!even.isEmpty else { return [] }
let min = even.min()!
let index = arr.firstIndex(of: min)!
return [min, index]
}
```
guard!even.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func pluck(arr: [Int]) -> [Int] {
let even = arr.filter { $0 % 2 == 0 }
guard!even.isEmpty else { return [] }
let min = even.min()!
let index = arr.firstIndex(of: min)!
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] {
let even = arr.filter { $0 % 2 == 0 }
guard!even.isEmpty else { return [] }
let min = even.min()!
let index = arr.firstIndex(of: min)!
return [min, index]
}
```
guard!even.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func pluck(arr: [Int]) -> [Int] {
var min = Int.max
var minIndex = -1
for (i, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = i
}
}
return [min, minIndex]
}
```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 min = Int.max
var minIndex = -1
for (i, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = i
}
}
return [min, minIndex]
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var min = Int.max
var minIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
return minIndex == -1? [] : [min, minIndex]
}
```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 min = Int.max
var minIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
return minIndex == -1? [] : [min, minIndex]
}
```
return minIndex == -1? [] : [min, minIndex] // expected expression
return minIndex == -1? [] : [min, minIndex] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return minIndex == -1? [] : [min, minIndex] // consecutive statements on a line must be separated by ';'
return minIndex == -1? [] : [min, minIndex] // value of type 'Int' has no subscripts
return minIndex == -1? [] : [min, minIndex] // cannot convert return expression of type 'Bool' to return type '[Int]'
return minIndex == -1? [] : [min, minIndex] // cannot use optional chaining on non-optional value of type 'Int'
func pluck(arr: [Int]) -> [Int] {
let minEven = arr.filter { $0 % 2 == 0 }.min()
guard let minEvenValue = minEven else { return [] }
let minEvenIndex = arr.firstIndex(of: minEvenValue)
return [minEvenValue, 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] {
let minEven = arr.filter { $0 % 2 == 0 }.min()
guard let minEvenValue = minEven else { return [] }
let minEvenIndex = arr.firstIndex(of: minEvenValue)
return [minEvenValue, minEvenIndex!]
}
```
func pluck(arr: [Int]) -> [Int] {
var min = Int.max
var minIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
return minIndex == -1? [] : [min, minIndex]
}
```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 min = Int.max
var minIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
return minIndex == -1? [] : [min, minIndex]
}
```
return minIndex == -1? [] : [min, minIndex] // expected expression
return minIndex == -1? [] : [min, minIndex] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return minIndex == -1? [] : [min, minIndex] // consecutive statements on a line must be separated by ';'
return minIndex == -1? [] : [min, minIndex] // value of type 'Int' has no subscripts
return minIndex == -1? [] : [min, minIndex] // cannot convert return expression of type 'Bool' to return type '[Int]'
return minIndex == -1? [] : [min, minIndex] // cannot use optional chaining on non-optional value of type 'Int'
func pluck(arr: [Int]) -> [Int] {
let minEven = arr.filter { $0 % 2 == 0 }.min()
let minEvenIndex = arr.firstIndex(of: minEven!)
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] {
let minEven = arr.filter { $0 % 2 == 0 }.min()
let minEvenIndex = arr.firstIndex(of: minEven!)
return [minEven!, minEvenIndex!]
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func pluck(arr: [Int]) -> [Int] {
var min = Int.max
var index = -1
for (i, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
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] {
var min = Int.max
var index = -1
for (i, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
index = i
}
}
return [min, index]
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var min = Int.max
var index = -1
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] {
var min = Int.max
var index = -1
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num]?? 0) + 1
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key {
result = max(result, key)
}
}
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 dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num]?? 0) + 1
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key {
result = max(result, key)
}
}
return result
}
```
dict[num] = (dict[num]?? 0) + 1 // expected ',' separator
dict[num] = (dict[num]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[num] = (dict[num]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
for (key, value) in dict {
if value > key {
return key
}
}
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 dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
for (key, value) in dict {
if value > key {
return key
}
}
return -1
}
```
dict[i] = (dict[i]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[i] = (dict[i]?? 0) + 1 // expected ',' separator
dict[i] = (dict[i]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
for i in lst.sorted(by: >) {
if dict[i]! >= i {
return i
}
}
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 dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
for i in lst.sorted(by: >) {
if dict[i]! >= i {
return i
}
}
return -1
}
```
dict[i] = (dict[i]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[i] = (dict[i]?? 0) + 1 // expected ',' separator
dict[i] = (dict[i]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key && (result == -1 || result < key) {
result = key
}
}
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 dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key && (result == -1 || result < key) {
result = key
}
}
return result
}
```
dict[i] = (dict[i]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[i] = (dict[i]?? 0) + 1 // expected ',' separator
dict[i] = (dict[i]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key && key > result {
result = key
}
}
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 dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key && key > result {
result = key
}
}
return result
}
```
dict[i] = (dict[i]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[i] = (dict[i]?? 0) + 1 // expected ',' separator
dict[i] = (dict[i]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
var max = 0
for (key, value) in dict {
if value > max && key > max {
max = key
}
}
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 dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
var max = 0
for (key, value) in dict {
if value > max && key > max {
max = key
}
}
return max
}
```
dict[i] = (dict[i]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[i] = (dict[i]?? 0) + 1 // expected ',' separator
dict[i] = (dict[i]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var result = -1
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
for (key, value) in dict {
if value > key {
result = max(result, key)
}
}
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 dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i]?? 0) + 1
}
for (key, value) in dict {
if value > key {
result = max(result, key)
}
}
return result
}
```
dict[i] = (dict[i]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[i] = (dict[i]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[i] = (dict[i]?? 0) + 1 // expected ',' separator
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
var max = 0
for (key, value) in dict {
if value > max && key > max {
max = key
}
}
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 dict = [Int: Int]()
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
var max = 0
for (key, value) in dict {
if value > max && key > max {
max = key
}
}
return max
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
}
var result = -1
for (key, value) in dict {
if value > key {
result = key
}
}
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 dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
}
var result = -1
for (key, value) in dict {
if value > key {
result = key
}
}
return result
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key {
result = max(result, key)
}
}
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 dict = [Int: Int]()
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
var result = -1
for (key, value) in dict {
if key > 0 && value >= key {
result = max(result, key)
}
}
return result
}
```
func strangeSortList(lst: [Int]) -> [Int] {
var list = lst
var result = [Int]()
var min = list.min()
var max = list.max()
while list.count > 0 {
if let min = min {
result.append(min)
list.remove(min)
min = list.min()
}
if let max = max {
result.append(max)
list.remove(max)
max = list.max()
}
}
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 list = lst
var result = [Int]()
var min = list.min()
var max = list.max()
while list.count > 0 {
if let min = min {
result.append(min)
list.remove(min)
min = list.min()
}
if let max = max {
result.append(max)
list.remove(max)
max = list.max()
}
}
return result
}
```
list.remove(min) // no exact matches in call to instance method 'remove'
min = list.min() // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
min = list.min() // cannot assign to value: 'min' is a 'let' constant
list.remove(max) // no exact matches in call to instance method 'remove'
max = list.max() // cannot assign to value: 'max' is a 'let' constant
max = list.max() // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list = list.filter { $0!= min }
let max = list.max()!
result.append(max)
list = list.filter { $0!= max }
}
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 = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list = list.filter { $0!= min }
let max = list.max()!
result.append(max)
list = list.filter { $0!= max }
}
return result
}
```
list = list.filter { $0!= min } // cannot force unwrap value of non-optional type 'Int'
list = list.filter { $0!= min } // '=' must have consistent whitespace on both sides
list = list.filter { $0!= max } // '=' must have consistent whitespace on both sides
list = list.filter { $0!= max } // cannot force unwrap value of non-optional type 'Int'
func strangeSortList(lst: [Int]) -> [Int] {
var list = lst
var result = [Int]()
while list.count > 0 {
let min = list.min()!
result.append(min)
list = list.filter { $0!= min }
let max = list.max()!
result.append(max)
list = list.filter { $0!= max }
}
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 list = lst
var result = [Int]()
while list.count > 0 {
let min = list.min()!
result.append(min)
list = list.filter { $0!= min }
let max = list.max()!
result.append(max)
list = list.filter { $0!= max }
}
return result
}
```
list = list.filter { $0!= min } // cannot force unwrap value of non-optional type 'Int'
list = list.filter { $0!= min } // '=' must have consistent whitespace on both sides
list = list.filter { $0!= max } // '=' must have consistent whitespace on both sides
list = list.filter { $0!= max } // cannot force unwrap value of non-optional type 'Int'
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var temp = lst
while temp.count > 0 {
result.append(temp.min()!)
temp.remove(at: temp.index(of: temp.min()!)!)
if temp.count > 0 {
result.append(temp.max()!)
temp.remove(at: temp.index(of: temp.max()!)!)
}
}
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 = [Int]()
var temp = lst
while temp.count > 0 {
result.append(temp.min()!)
temp.remove(at: temp.index(of: temp.min()!)!)
if temp.count > 0 {
result.append(temp.max()!)
temp.remove(at: temp.index(of: temp.max()!)!)
}
}
return result
}
```
temp.remove(at: temp.index(of: temp.min()!)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
temp.remove(at: temp.index(of: temp.max()!)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
func strangeSortList(lst: [Int]) -> [Int] {
var list = lst
var newList = [Int]()
var min = list.min()
var max = list.max()
while list.count > 0 {
if list.count == 1 {
newList.append(list[0])
list.remove(at: 0)
} else {
newList.append(min!)
list.remove(at: list.index(of: min!)!)
newList.append(max!)
list.remove(at: list.index(of: max!)!)
min = list.min()
max = list.max()
}
}
return newList
}
```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 list = lst
var newList = [Int]()
var min = list.min()
var max = list.max()
while list.count > 0 {
if list.count == 1 {
newList.append(list[0])
list.remove(at: 0)
} else {
newList.append(min!)
list.remove(at: list.index(of: min!)!)
newList.append(max!)
list.remove(at: list.index(of: max!)!)
min = list.min()
max = list.max()
}
}
return newList
}
```
list.remove(at: list.index(of: min!)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
list.remove(at: list.index(of: max!)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list.remove(at: list.firstIndex(of: min)!)
if list.count > 0 {
let max = list.max()!
result.append(max)
list.remove(at: list.firstIndex(of: max)!)
}
}
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 = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list.remove(at: list.firstIndex(of: min)!)
if list.count > 0 {
let max = list.max()!
result.append(max)
list.remove(at: list.firstIndex(of: max)!)
}
}
return result
}
```
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list.remove(at: list.index(of: min)!)
if list.count > 0 {
let max = list.max()!
result.append(max)
list.remove(at: list.index(of: max)!)
}
}
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 = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list.remove(at: list.index(of: min)!)
if list.count > 0 {
let max = list.max()!
result.append(max)
list.remove(at: list.index(of: max)!)
}
}
return result
}
```
list.remove(at: list.index(of: min)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
list.remove(at: list.index(of: max)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
func strangeSortList(lst: [Int]) -> [Int] {
// TODO: Implement me!
return []
}
```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] {
// TODO: Implement me!
return []
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list.remove(at: list.firstIndex(of: min)!)
let max = list.max()!
result.append(max)
list.remove(at: list.firstIndex(of: max)!)
}
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 = [Int]()
var list = lst
while list.count > 0 {
let min = list.min()!
result.append(min)
list.remove(at: list.firstIndex(of: min)!)
let max = list.max()!
result.append(max)
list.remove(at: list.firstIndex(of: max)!)
}
return result
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
```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 = [Int]()
var min = lst[0]
var max = lst[0]
var minIndex = 0
var maxIndex = 0
var minIndex2 = 0
var maxIndex2 = 0
var minIndex3 = 0
var maxIndex3 = 0
var minIndex4 = 0
var maxIndex4 = 0
var minIndex5 = 0
var maxIndex5 = 0
var minIndex6 = 0
var maxIndex6 = 0
var minIndex7 = 0
var maxIndex7 = 0
var minIndex8 = 0
var maxIndex8 = 0
var minIndex9 = 0
var maxIndex9 = 0
var minIndex10 = 0
var maxIndex10 = 0
var minIndex11 = 0
var maxIndex11 = 0
var minIndex12 = 0
var maxIndex12 = 0
var minIndex13 = 0
var maxIndex13 = 0
var minIndex14 = 0
var maxIndex14 = 0
var minIndex15 = 0
var maxIndex15 = 0
var minIndex16 = 0
var maxIndex16 = 0
var minIndex17 = 0
var maxIndex17 = 0
var minIndex18 = 0
var maxIndex18 = 0
var minIndex19 = 0
var maxIndex19 = 0
var minIndex20 = 0
var maxIndex20 = 0
var minIndex21 = 0
var maxIndex21 = 0
var minIndex22 = 0
var maxIndex22 = 0
var minIndex23 = 0
var maxIndex23 = 0
var minIndex24 = 0
var maxIndex24 = 0
var minIndex25 = 0
var maxIndex25 = 0
var minIndex26 = 0
var maxIndex26 = 0
var minIndex27 = 0
var maxIndex27 = 0
var minIndex28 = 0
var maxIndex28 = 0
var minIndex29 = 0
var maxIndex29 = 0
var minIndex30 = 0
var maxIndex30 = 0
var minIndex31 = 0
var maxIndex31 = 0
var minIndex32 = 0
var maxIndex32 = 0
var minIndex33 = 0
var maxIndex33 = 0
var minIndex34 = 0
var maxIndex34 = 0
var minIndex35 = 0
var maxIndex35 = 0
var minIndex36 = 0
var maxIndex36 = 0
var minIndex37 = 0
var maxIndex37 = 0
var minIndex38 = 0
var maxIndex38 = 0
var minIndex39 = 0
var maxIndex39 = 0
var minIndex40 = 0
var maxIndex40 = 0
var minIndex41 = 0
var maxIndex41 = 0
var minIndex42 = 0
var maxIndex42 = 0
var minIndex43 = 0
var maxIndex43 = 0
var minIndex44 = 0
var maxIndex44 = 0
var minIndex45 = 0
var maxIndex45 = 0
var minIndex46 = 0
var maxIndex46 = 0
var minIndex47 = 0
var maxIndex47 = 0
var minIndex48 = 0
var maxIndex48 = 0
var minIndex49 = 0
var maxIndex49 = 0
var minIndex50 = 0
var maxIndex50 = 0
var minIndex51 = 0
var maxIndex51 = 0
var minIndex52 = 0
var maxIndex52 = 0
var minIndex53 = 0
var maxIndex53 = 0
var minIndex54 = 0
var maxIndex54 = 0
var minIndex55 = 0
var maxIndex55 = 0
var minIndex56 = 0
var maxIndex56 = 0
var minIndex57 = 0
var maxIndex
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [] as [Int]) == [] as [Int]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8]) == [1, 8, 2, 7, 3, 6, 4, 5]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [0, 2, 2, 2, 5, 5, -5, -5]) == [-5, 5, -5, 5, 0, 2, 2, 2]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [111111]) == [111111]) // cannot find 'strangeSortList' in scope
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && a + c > b && b + c > a {
let p = (a + b + c) / 2
return sqrt(Double(p) * (Double(p) - Double(a)) * (Double(p) - Double(b)) * (Double(p) - Double(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 && a + c > b && b + c > a {
let p = (a + b + c) / 2
return sqrt(Double(p) * (Double(p) - Double(a)) * (Double(p) - Double(b)) * (Double(p) - Double(c)))
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sortedSides = sides.sorted()
let sumOfShortestTwoSides = sortedSides[0] + sortedSides[1]
if sumOfShortestTwoSides > sortedSides[2] {
let p = (sortedSides[0] + sortedSides[1] + sortedSides[2]) / 2
let area = sqrt(p * (p - sortedSides[0]) * (p - sortedSides[1]) * (p - sortedSides[2]))
return area
} 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 {
let sides = [a, b, c]
let sortedSides = sides.sorted()
let sumOfShortestTwoSides = sortedSides[0] + sortedSides[1]
if sumOfShortestTwoSides > sortedSides[2] {
let p = (sortedSides[0] + sortedSides[1] + sortedSides[2]) / 2
let area = sqrt(p * (p - sortedSides[0]) * (p - sortedSides[1]) * (p - sortedSides[2]))
return area
} else {
return -1
}
}
```
let area = sqrt(p * (p - sortedSides[0]) * (p - sortedSides[1]) * (p - sortedSides[2])) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && a + c > b && b + c > a {
let p = (a + b + c) / 2
let area = sqrt(p * (p - a) * (p - b) * (p - c))
return area
} 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 && a + c > b && b + c > a {
let p = (a + b + c) / 2
let area = sqrt(p * (p - a) * (p - b) * (p - c))
return area
} else {
return -1
}
}
```
let area = 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 {
let sides = [a, b, c]
let sortedSides = sides.sorted()
let sum = sortedSides[0] + sortedSides[1]
if sum > sortedSides[2] {
let p = (sortedSides[0] + sortedSides[1] + sortedSides[2]) / 2
let area = sqrt(p * (p - sortedSides[0]) * (p - sortedSides[1]) * (p - sortedSides[2]))
return area
} 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 {
let sides = [a, b, c]
let sortedSides = sides.sorted()
let sum = sortedSides[0] + sortedSides[1]
if sum > sortedSides[2] {
let p = (sortedSides[0] + sortedSides[1] + sortedSides[2]) / 2
let area = sqrt(p * (p - sortedSides[0]) * (p - sortedSides[1]) * (p - sortedSides[2]))
return area
} else {
return -1
}
}
```
let area = sqrt(p * (p - sortedSides[0]) * (p - sortedSides[1]) * (p - sortedSides[2])) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sortedSides = sides.sorted()
if sortedSides[0] + sortedSides[1] > sortedSides[2] {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
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 {
let sides = [a, b, c]
let sortedSides = sides.sorted()
if sortedSides[0] + sortedSides[1] > sortedSides[2] {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
return -1
}
```
let area = 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 sides = [a, b, c]
let sorted = sides.sorted()
if sorted[0] + sorted[1] > sorted[2] {
let p = (sorted[0] + sorted[1] + sorted[2]) / 2
return sqrt(p * (p - sorted[0]) * (p - sorted[1]) * (p - sorted[2]))
} 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 {
let sides = [a, b, c]
let sorted = sides.sorted()
if sorted[0] + sorted[1] > sorted[2] {
let p = (sorted[0] + sorted[1] + sorted[2]) / 2
return sqrt(p * (p - sorted[0]) * (p - sorted[1]) * (p - sorted[2]))
} else {
return -1
}
}
```
return sqrt(p * (p - sorted[0]) * (p - sorted[1]) * (p - sorted[2])) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sortedSides = sides.sorted()
let (s1, s2, s3) = (sortedSides[0], sortedSides[1], sortedSides[2])
if s1 + s2 > s3 {
let p = (s1 + s2 + s3) / 2
return sqrt(p * (p - Double(s1)) * (p - Double(s2)) * (p - Double(s3)))
}
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 {
let sides = [a, b, c]
let sortedSides = sides.sorted()
let (s1, s2, s3) = (sortedSides[0], sortedSides[1], sortedSides[2])
if s1 + s2 > s3 {
let p = (s1 + s2 + s3) / 2
return sqrt(p * (p - Double(s1)) * (p - Double(s2)) * (p - Double(s3)))
}
return -1
}
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sorted = sides.sorted()
if sorted[0] + sorted[1] > sorted[2] {
let p = (sorted[0] + sorted[1] + sorted[2]) / 2
let area = sqrt(p * (p - Double(sorted[0])) * (p - Double(sorted[1])) * (p - Double(sorted[2])))
return area
} 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 {
let sides = [a, b, c]
let sorted = sides.sorted()
if sorted[0] + sorted[1] > sorted[2] {
let p = (sorted[0] + sorted[1] + sorted[2]) / 2
let area = sqrt(p * (p - Double(sorted[0])) * (p - Double(sorted[1])) * (p - Double(sorted[2])))
return area
} else {
return -1
}
}
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sorted = sides.sorted()
if sorted[0] + sorted[1] > sorted[2] {
let p = (sorted[0] + sorted[1] + sorted[2]) / 2
let area = sqrt(p * (p - Double(sorted[0])) * (p - Double(sorted[1])) * (p - Double(sorted[2])))
return area
} 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 {
let sides = [a, b, c]
let sorted = sides.sorted()
if sorted[0] + sorted[1] > sorted[2] {
let p = (sorted[0] + sorted[1] + sorted[2]) / 2
let area = sqrt(p * (p - Double(sorted[0])) * (p - Double(sorted[1])) * (p - Double(sorted[2])))
return area
} else {
return -1
}
}
```
func willItFly(q: [Int], w: Int) -> Bool {
return q.isPalindrome && q.sum() <= w
}
```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.isPalindrome && q.sum() <= w
}
```
return q.isPalindrome && q.sum() <= w // value of type '[Int]' has no member 'sum'
return q.isPalindrome && q.sum() <= w // value of type '[Int]' has no member 'isPalindrome'
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = q.count * w
return sum <= maxWeight && q.sorted() == q
}
```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 {
let sum = q.reduce(0, +)
let maxWeight = q.count * w
return sum <= maxWeight && q.sorted() == q
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = q.count * w
return sum <= maxWeight && q.sorted() == q
}
```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 {
let sum = q.reduce(0, +)
let maxWeight = q.count * w
return sum <= maxWeight && q.sorted() == q
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = q.count * w
return sum <= max && q.sorted() == q.reversed()
}
```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 {
let sum = q.reduce(0, +)
let max = q.count * w
return sum <= max && q.sorted() == q.reversed()
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return q.count == 1 || (sum <= w && q.sorted() == q.reversed())
}
```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 {
let sum = q.reduce(0, +)
return q.count == 1 || (sum <= w && q.sorted() == q.reversed())
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return q.count == 1 && sum <= w || q.count > 1 && sum <= w && q.sorted() == q.reversed()
}
```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 {
let sum = q.reduce(0, +)
return q.count == 1 && sum <= w || q.count > 1 && sum <= w && q.sorted() == q.reversed()
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return q.count == 1 && sum <= w || q.count > 1 && sum <= w && q.sorted() == q.reversed()
}
```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 {
let sum = q.reduce(0, +)
return q.count == 1 && sum <= w || q.count > 1 && sum <= w && q.sorted() == q.reversed()
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = q.count * w
return sum <= maxWeight && q.sorted() == q.reversed()
}
```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 {
let sum = q.reduce(0, +)
let maxWeight = q.count * w
return sum <= maxWeight && q.sorted() == q.reversed()
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q.sorted() == q.reversed()
}
```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 {
let sum = q.reduce(0, +)
return sum <= w && q.sorted() == q.reversed()
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = q.count * w
return sum <= max && q.sorted() == q.reversed()
}
```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 {
let sum = q.reduce(0, +)
let max = q.count * w
return sum <= max && q.sorted() == q.reversed()
}
```
// 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
}
```
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 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 i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
count += 1
if arr[left] < arr[right] {
arr[left] = arr[right]
} else {
arr[right] = arr[left]
}
}
}
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] {
left += 1
right -= 1
} else {
count += 1
if arr[left] < arr[right] {
arr[left] = arr[right]
} else {
arr[right] = arr[left]
}
}
}
return count
}
```
arr[left] = arr[right] // cannot assign through subscript: 'arr' is a 'let' constant
arr[right] = arr[left] // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 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 i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 1
}
return count
}
```
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
func smallestChange(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 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 i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 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 i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 1
}
return count
}
```
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
count += 1
left += 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] {
left += 1
right -= 1
} else {
count += 1
left += 1
}
}
return count
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var dict = [Int: Int]()
for num in arr {
if let value = dict[num] {
dict[num] = value + 1
} else {
dict[num] = 1
}
}
var oddCount = 0
for (_, value) in dict {
if value % 2!= 0 {
oddCount += 1
}
}
if oddCount > 1 {
return oddCount - 1
} else {
return 0
}
}
```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 dict = [Int: Int]()
for num in arr {
if let value = dict[num] {
dict[num] = value + 1
} else {
dict[num] = 1
}
}
var oddCount = 0
for (_, value) in dict {
if value % 2!= 0 {
oddCount += 1
}
}
if oddCount > 1 {
return oddCount - 1
} else {
return 0
}
}
```
if value % 2!= 0 { // '=' must have consistent whitespace on both sides
if value % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if value % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if value % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
while!isPalindrome(arr: arr) {
let first = arr.removeFirst()
let last = arr.removeLast()
arr.insert(first, at: 0)
arr.insert(last, at: arr.count)
count += 1
}
return count
}
func isPalindrome(arr: [Int]) -> Bool {
var arr = arr
while arr.count > 1 {
let first = arr.removeFirst()
let last = arr.removeLast()
if first!= last {
return false
}
}
return true
}
```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 arr = arr
while!isPalindrome(arr: arr) {
let first = arr.removeFirst()
let last = arr.removeLast()
arr.insert(first, at: 0)
arr.insert(last, at: arr.count)
count += 1
}
return count
}
func isPalindrome(arr: [Int]) -> Bool {
var arr = arr
while arr.count > 1 {
let first = arr.removeFirst()
let last = arr.removeLast()
if first!= last {
return false
}
}
return true
}
```
while!isPalindrome(arr: arr) { // expected expression, var, or let in 'while' condition
if first!= last { // cannot force unwrap value of non-optional type 'Int'
if first!= last { // '=' must have consistent whitespace on both sides
if first!= last { // use of '=' in a boolean context, did you mean '=='?
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
while!isPalindrome(arr: arr) {
arr = arr.map { $0 == arr[0]? arr[arr.count - 1] : $0 }
count += 1
}
return count
}
func isPalindrome(arr: [Int]) -> Bool {
var arr = arr
while arr.count > 1 {
if arr[0]!= arr[arr.count - 1] {
return false
}
arr.removeFirst()
arr.removeLast()
}
return true
}
```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 arr = arr
while!isPalindrome(arr: arr) {
arr = arr.map { $0 == arr[0]? arr[arr.count - 1] : $0 }
count += 1
}
return count
}
func isPalindrome(arr: [Int]) -> Bool {
var arr = arr
while arr.count > 1 {
if arr[0]!= arr[arr.count - 1] {
return false
}
arr.removeFirst()
arr.removeLast()
}
return true
}
```
while!isPalindrome(arr: arr) { // expected expression, var, or let in 'while' condition
if arr[0]!= arr[arr.count - 1] { // cannot force unwrap value of non-optional type 'Int'
if arr[0]!= arr[arr.count - 1] { // use of '=' in a boolean context, did you mean '=='?
if arr[0]!= arr[arr.count - 1] { // '=' must have consistent whitespace on both sides
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result: [String] = []
var total1 = 0
var total2 = 0
for str in lst1 {
total1 += str.count
}
for str in lst2 {
total2 += str.count
}
if total1 < total2 {
result = lst1
} else if total1 > total2 {
result = lst2
} else {
result = lst1
}
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: [String] = []
var total1 = 0
var total2 = 0
for str in lst1 {
total1 += str.count
}
for str in lst2 {
total2 += str.count
}
if total1 < total2 {
result = lst1
} else if total1 > total2 {
result = lst2
} else {
result = lst1
}
return result
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var total1 = 0
var total2 = 0
for str in lst1 {
total1 += str.count
}
for str in lst2 {
total2 += str.count
}
if total1 < total2 {
result = lst1
} else if total1 > total2 {
result = lst2
} else {
result = lst1
}
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 = [String]()
var total1 = 0
var total2 = 0
for str in lst1 {
total1 += str.count
}
for str in lst2 {
total2 += str.count
}
if total1 < total2 {
result = lst1
} else if total1 > total2 {
result = lst2
} else {
result = lst1
}
return result
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result: [String] = []
var sum1 = 0
var sum2 = 0
for i in lst1 {
sum1 += i.count
}
for i in lst2 {
sum2 += i.count
}
if sum1 < sum2 {
result = lst1
} else if sum1 > sum2 {
result = lst2
} else {
result = lst1
}
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: [String] = []
var sum1 = 0
var sum2 = 0
for i in lst1 {
sum1 += i.count
}
for i in lst2 {
sum2 += i.count
}
if sum1 < sum2 {
result = lst1
} else if sum1 > sum2 {
result = lst2
} else {
result = lst1
}
return result
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total1 > total2 {
return lst2
} else {
return lst1
}
}
```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 total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total1 > total2 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
let total1 = lst1.reduce(0) { $0 + $1.count }
let total2 = lst2.reduce(0) { $0 + $1.count }
if total1 < total2 {
result = lst1
} else if total1 > total2 {
result = lst2
} else {
result = lst1
}
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 = [String]()
let total1 = lst1.reduce(0) { $0 + $1.count }
let total2 = lst2.reduce(0) { $0 + $1.count }
if total1 < total2 {
result = lst1
} else if total1 > total2 {
result = lst2
} else {
result = lst1
}
return result
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total1 > total2 {
return lst2
} else {
return lst1
}
}
```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 total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total1 > total2 {
return lst2
} else {
return lst1
}
}
```
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```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 {
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```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 {
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```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 {
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0 && n > 0 else { return false }
var result = 1
while result < x {
result *= n
}
return result == 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 {
guard x > 0 && n > 0 else { return false }
var result = 1
while result < x {
result *= n
}
return result == x
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isSimplePower(x: Int, n: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func iscube(a: Int) -> Bool {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func iscube(a: Int) -> Bool {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
var i = 0
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 0
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 1
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
let cube = Int(pow(Double(a), 1.0/3.0))
return cube * cube * cube == 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 cube = Int(pow(Double(a), 1.0/3.0))
return cube * cube * cube == a
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
var i = 0
while i * i * i < a {
i += 1
}
return i * i * i == 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 {
var i = 0
while i * i * i < a {
i += 1
}
return i * i * i == a
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
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 {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
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 {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
return num.filter { hex.contains($0) }.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 = "0123456789ABCDEF"
return num.filter { hex.contains($0) }.count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for char in num {
if hex.contains(char) {
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 = "0123456789ABCDEF"
var count = 0
for char in num {
if hex.contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15]
var count = 0
for char in num {
if hex[String(char)]! % 2 == 1 || hex[String(char)]! % 3 == 1 {
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": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15]
var count = 0
for char in num {
if hex[String(char)]! % 2 == 1 || hex[String(char)]! % 3 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
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 {
let hex = "0123456789ABCDEF"
var count = 0
for char in num {
if hex.contains(String(char)) {
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 = "0123456789ABCDEF"
var count = 0
for char in num {
if hex.contains(String(char)) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
let hexArray = Array(hex)
var count = 0
for char in num {
if hexArray.contains(char) {
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 = "0123456789ABCDEF"
let hexArray = Array(hex)
var count = 0
for char in num {
if hexArray.contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
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 {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
var count = 0
for char in num {
if let index = hex.firstIndex(of: char) {
if primes[index.encodedOffset] == 1 {
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 = "0123456789ABCDEF"
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
var count = 0
for char in num {
if let index = hex.firstIndex(of: char) {
if primes[index.encodedOffset] == 1 {
count += 1
}
}
}
return count
}
```
if primes[index.encodedOffset] == 1 { // 'encodedOffset' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)" + result
number /= 2
}
return "db" + result + "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 result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)" + result
number /= 2
}
return "db" + result + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var number = decimal
while number > 0 {
binary = "\(number % 2)\(binary)"
number /= 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 = ""
var number = decimal
while number > 0 {
binary = "\(number % 2)\(binary)"
number /= 2
}
return "db\(binary)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)\(result)"
number /= 2
}
return "db\(result)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 result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)\(result)"
number /= 2
}
return "db\(result)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var number = decimal
while number > 0 {
binary = "\(number % 2)\(binary)"
number /= 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 = ""
var number = decimal
while number > 0 {
binary = "\(number % 2)\(binary)"
number /= 2
}
return "db\(binary)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = "\(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 = ""
var decimal = decimal
while decimal > 0 {
binary = "\(decimal % 2)\(binary)"
decimal /= 2
}
return "db\(binary)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)\(result)"
number /= 2
}
return "db\(result)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 result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)\(result)"
number /= 2
}
return "db\(result)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)\(result)"
number /= 2
}
return "db\(result)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 result = ""
var number = decimal
while number > 0 {
result = "\(number % 2)\(result)"
number /= 2
}
return "db\(result)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var remainder = decimal
while remainder > 0 {
result = String(remainder % 2) + result
remainder /= 2
}
return "db" + result + "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 result = ""
var remainder = decimal
while remainder > 0 {
result = String(remainder % 2) + result
remainder /= 2
}
return "db" + result + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
return "db" + String(decimal, radix: 2) + "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 {
return "db" + String(decimal, radix: 2) + "db"
}
```
func decimalToBinary(decimal: Int) -> String {
return String(decimal, radix: 2)
}
```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 {
return String(decimal, radix: 2)
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for i in 0..<s.count {
if i + 2 < s.count {
set.insert(s[i])
set.insert(s[i+1])
set.insert(s[i+2])
}
}
return set.count == s.count
}
```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 set = Set<Character>()
for i in 0..<s.count {
if i + 2 < s.count {
set.insert(s[i])
set.insert(s[i+1])
set.insert(s[i+2])
}
}
return set.count == s.count
}
```
set.insert(s[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i+1]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i+2]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count - 2 {
let sub = s[i..<i+3]
if set.contains(sub) { return false }
set.insert(sub)
}
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 {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count - 2 {
let sub = s[i..<i+3]
if set.contains(sub) { return false }
set.insert(sub)
}
return true
}
```
let sub = s[i..<i+3] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
set.insert(sub) // cannot convert value of type 'String' to expected argument type 'Character'
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for i in 0..<s.count {
if i + 2 < s.count {
set.insert(s[i])
set.insert(s[i + 1])
set.insert(s[i + 2])
}
}
return set.count == s.count
}
```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 set = Set<Character>()
for i in 0..<s.count {
if i + 2 < s.count {
set.insert(s[i])
set.insert(s[i + 1])
set.insert(s[i + 2])
}
}
return set.count == s.count
}
```
set.insert(s[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i + 1]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i + 2]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
var dict = [Character: Int]()
for char in s {
if dict[char] == nil {
dict[char] = 1
} else {
dict[char]! += 1
}
}
for (char, count) in dict {
if count > 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 {
var dict = [Character: Int]()
for char in s {
if dict[char] == nil {
dict[char] = 1
} else {
dict[char]! += 1
}
}
for (char, count) in dict {
if count > 1 {
return false
}
}
return true
}
```
for (char, count) in dict { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count - 2 {
set.insert(s[s.index(s.startIndex, offsetBy: i)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 1)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 2)])
if set.count == 3 {
return true
}
set.removeAll()
}
return false
}
```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 {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count - 2 {
set.insert(s[s.index(s.startIndex, offsetBy: i)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 1)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 2)])
if set.count == 3 {
return true
}
set.removeAll()
}
return false
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var dict = [Character: Int]()
for char in s {
if dict[char] == nil {
dict[char] = 1
} else {
dict[char]! += 1
}
}
for (_, value) in dict {
if value > 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 {
var dict = [Character: Int]()
for char in s {
if dict[char] == nil {
dict[char] = 1
} else {
dict[char]! += 1
}
}
for (_, value) in dict {
if value > 1 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count - 2 {
set.insert(s[s.index(s.startIndex, offsetBy: i)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 1)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 2)])
if set.count!= 3 { return false }
set.removeAll()
}
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 {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count - 2 {
set.insert(s[s.index(s.startIndex, offsetBy: i)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 1)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 2)])
if set.count!= 3 { return false }
set.removeAll()
}
return true
}
```
if set.count!= 3 { return false } // '=' must have consistent whitespace on both sides
if set.count!= 3 { return false } // use of '=' in a boolean context, did you mean '=='?
if set.count!= 3 { return false } // cannot force unwrap value of non-optional type 'Int'
func isHappy(s: String) -> Bool {
var dict = [Character: Int]()
for char in s {
if dict[char] == nil {
dict[char] = 1
} else {
dict[char]! += 1
}
}
for (key, value) in dict {
if value > 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 {
var dict = [Character: Int]()
for char in s {
if dict[char] == nil {
dict[char] = 1
} else {
dict[char]! += 1
}
}
for (key, value) in dict {
if value > 1 {
return false
}
}
return true
}
```
for (key, value) in dict { // immutable value 'key' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count {
if i + 2 < s.count {
set.insert(s[s.index(s.startIndex, offsetBy: i)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 1)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 2)])
}
if set.count == 3 { return true }
set.removeAll()
}
return false
}
```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 {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in 0..<s.count {
if i + 2 < s.count {
set.insert(s[s.index(s.startIndex, offsetBy: i)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 1)])
set.insert(s[s.index(s.startIndex, offsetBy: i + 2)])
}
if set.count == 3 { return true }
set.removeAll()
}
return false
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for gpa in grades {
if gpa >= 4.0 {
letterGrades.append("A+")
} else if gpa >= 3.7 {
letterGrades.append("A")
} else if gpa >= 3.3 {
letterGrades.append("A-")
} else if gpa >= 3.0 {
letterGrades.append("B+")
} else if gpa >= 2.7 {
letterGrades.append("B")
} else if gpa >= 2.3 {
letterGrades.append("B-")
} else if gpa >= 2.0 {
letterGrades.append("C+")
} else if gpa >= 1.7 {
letterGrades.append("C")
} else if gpa >= 1.3 {
letterGrades.append("C-")
} else if gpa >= 1.0 {
letterGrades.append("D+")
} else if gpa >= 0.7 {
letterGrades.append("D")
} else if gpa >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 letterGrades = [String]()
for gpa in grades {
if gpa >= 4.0 {
letterGrades.append("A+")
} else if gpa >= 3.7 {
letterGrades.append("A")
} else if gpa >= 3.3 {
letterGrades.append("A-")
} else if gpa >= 3.0 {
letterGrades.append("B+")
} else if gpa >= 2.7 {
letterGrades.append("B")
} else if gpa >= 2.3 {
letterGrades.append("B-")
} else if gpa >= 2.0 {
letterGrades.append("C+")
} else if gpa >= 1.7 {
letterGrades.append("C")
} else if gpa >= 1.3 {
letterGrades.append("C-")
} else if gpa >= 1.0 {
letterGrades.append("D+")
} else if gpa >= 0.7 {
letterGrades.append("D")
} else if gpa >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for gpa in grades {
if gpa >= 4.0 {
letterGrades.append("A+")
} else if gpa >= 3.7 {
letterGrades.append("A")
} else if gpa >= 3.3 {
letterGrades.append("A-")
} else if gpa >= 3.0 {
letterGrades.append("B+")
} else if gpa >= 2.7 {
letterGrades.append("B")
} else if gpa >= 2.3 {
letterGrades.append("B-")
} else if gpa >= 2.0 {
letterGrades.append("C+")
} else if gpa >= 1.7 {
letterGrades.append("C")
} else if gpa >= 1.3 {
letterGrades.append("C-")
} else if gpa >= 1.0 {
letterGrades.append("D+")
} else if gpa >= 0.7 {
letterGrades.append("D")
} else if gpa >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 letterGrades = [String]()
for gpa in grades {
if gpa >= 4.0 {
letterGrades.append("A+")
} else if gpa >= 3.7 {
letterGrades.append("A")
} else if gpa >= 3.3 {
letterGrades.append("A-")
} else if gpa >= 3.0 {
letterGrades.append("B+")
} else if gpa >= 2.7 {
letterGrades.append("B")
} else if gpa >= 2.3 {
letterGrades.append("B-")
} else if gpa >= 2.0 {
letterGrades.append("C+")
} else if gpa >= 1.7 {
letterGrades.append("C")
} else if gpa >= 1.3 {
letterGrades.append("C-")
} else if gpa >= 1.0 {
letterGrades.append("D+")
} else if gpa >= 0.7 {
letterGrades.append("D")
} else if gpa >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for gpa in grades {
if gpa >= 4.0 {
result.append("A+")
} else if gpa >= 3.7 {
result.append("A")
} else if gpa >= 3.3 {
result.append("A-")
} else if gpa >= 3.0 {
result.append("B+")
} else if gpa >= 2.7 {
result.append("B")
} else if gpa >= 2.3 {
result.append("B-")
} else if gpa >= 2.0 {
result.append("C+")
} else if gpa >= 1.7 {
result.append("C")
} else if gpa >= 1.3 {
result.append("C-")
} else if gpa >= 1.0 {
result.append("D+")
} else if gpa >= 0.7 {
result.append("D")
} else if gpa >= 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 gpa in grades {
if gpa >= 4.0 {
result.append("A+")
} else if gpa >= 3.7 {
result.append("A")
} else if gpa >= 3.3 {
result.append("A-")
} else if gpa >= 3.0 {
result.append("B+")
} else if gpa >= 2.7 {
result.append("B")
} else if gpa >= 2.3 {
result.append("B-")
} else if gpa >= 2.0 {
result.append("C+")
} else if gpa >= 1.7 {
result.append("C")
} else if gpa >= 1.3 {
result.append("C-")
} else if gpa >= 1.0 {
result.append("D+")
} else if gpa >= 0.7 {
result.append("D")
} else if gpa >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
var letterGrades = [String]()
for i in 0..<grades.count {
if grades[i] >= 4.0 {
letterGrades.append("A+")
} else if grades[i] >= 3.7 {
letterGrades.append("A")
} else if grades[i] >= 3.3 {
letterGrades.append("A-")
} else if grades[i] >= 3.0 {
letterGrades.append("B+")
} else if grades[i] >= 2.7 {
letterGrades.append("B")
} else if grades[i] >= 2.3 {
letterGrades.append("B-")
} else if grades[i] >= 2.0 {
letterGrades.append("C+")
} else if grades[i] >= 1.7 {
letterGrades.append("C")
} else if grades[i] >= 1.3 {
letterGrades.append("C-")
} else if grades[i] >= 1.0 {
letterGrades.append("D+")
} else if grades[i] >= 0.7 {
letterGrades.append("D")
} else if grades[i] >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```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 grades = grades
var letterGrades = [String]()
for i in 0..<grades.count {
if grades[i] >= 4.0 {
letterGrades.append("A+")
} else if grades[i] >= 3.7 {
letterGrades.append("A")
} else if grades[i] >= 3.3 {
letterGrades.append("A-")
} else if grades[i] >= 3.0 {
letterGrades.append("B+")
} else if grades[i] >= 2.7 {
letterGrades.append("B")
} else if grades[i] >= 2.3 {
letterGrades.append("B-")
} else if grades[i] >= 2.0 {
letterGrades.append("C+")
} else if grades[i] >= 1.7 {
letterGrades.append("C")
} else if grades[i] >= 1.3 {
letterGrades.append("C-")
} else if grades[i] >= 1.0 {
letterGrades.append("D+")
} else if grades[i] >= 0.7 {
letterGrades.append("D")
} else if grades[i] >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
var grades = grades // variable 'grades' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for gpa in grades {
if gpa >= 4.0 {
result.append("A+")
} else if gpa >= 3.7 {
result.append("A")
} else if gpa >= 3.3 {
result.append("A-")
} else if gpa >= 3.0 {
result.append("B+")
} else if gpa >= 2.7 {
result.append("B")
} else if gpa >= 2.3 {
result.append("B-")
} else if gpa >= 2.0 {
result.append("C+")
} else if gpa >= 1.7 {
result.append("C")
} else if gpa >= 1.3 {
result.append("C-")
} else if gpa >= 1.0 {
result.append("D+")
} else if gpa >= 0.7 {
result.append("D")
} else if gpa >= 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 gpa in grades {
if gpa >= 4.0 {
result.append("A+")
} else if gpa >= 3.7 {
result.append("A")
} else if gpa >= 3.3 {
result.append("A-")
} else if gpa >= 3.0 {
result.append("B+")
} else if gpa >= 2.7 {
result.append("B")
} else if gpa >= 2.3 {
result.append("B-")
} else if gpa >= 2.0 {
result.append("C+")
} else if gpa >= 1.7 {
result.append("C")
} else if gpa >= 1.3 {
result.append("C-")
} else if gpa >= 1.0 {
result.append("D+")
} else if gpa >= 0.7 {
result.append("D")
} else if gpa >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: implement
}
```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 {
// TODO: implement
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 10
}
let start = startsOneEnds(n: n - 1)
let end = startsOneEnds(n: n - 1)
return start + end
}
```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 10
}
let start = startsOneEnds(n: n - 1)
let end = startsOneEnds(n: n - 1)
return start + end
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: implement this function
}
```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 {
// TODO: implement this function
}
```
} // missing return in global function expected to return 'Int'
func startsOneEnds(n: Int) -> Int {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Int'
func solve(N: Int) -> String {
var result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```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 result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var number = N
while number > 0 {
result = "\(number % 2)" + result
number /= 2
}
return result
}
```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 result = ""
var number = N
while number > 0 {
result = "\(number % 2)" + result
number /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```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 n = N
var result = ""
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```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 result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var N = N
while N > 0 {
result = "\(N % 2)" + result
N /= 2
}
return result
}
```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 result = ""
var N = N
while N > 0 {
result = "\(N % 2)" + result
N /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```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 result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var num = N
while num > 0 {
result = "\(num % 2)" + result
num /= 2
}
return result
}
```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 result = ""
var num = N
while num > 0 {
result = "\(num % 2)" + result
num /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = "\(N % 2)" + result
N /= 2
}
return result
}
```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 N = N
var result = ""
while N > 0 {
result = "\(N % 2)" + result
N /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```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 n = N
var result = ""
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```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 result = ""
var n = N
while n > 0 {
result = "\(n % 2)" + result
n /= 2
}
return result
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
add(lst: [4, 2, 6, 7])
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
```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 temp = ""
var temp2 = ""
var temp3 = ""
var temp4 = ""
var temp5 = ""
var temp6 = ""
var temp7 = ""
var temp8 = ""
var temp9 = ""
var temp10 = ""
var temp11 = ""
var temp12 = ""
var temp13 = ""
var temp14 = ""
var temp15 = ""
var temp16 = ""
var temp17 = ""
var temp18 = ""
var temp19 = ""
var temp20 = ""
var temp21 = ""
var temp22 = ""
var temp23 = ""
var temp24 = ""
var temp25 = ""
var temp26 = ""
var temp27 = ""
var temp28 = ""
var temp29 = ""
var temp30 = ""
var temp31 = ""
var temp32 = ""
var temp33 = ""
var temp34 = ""
var temp35 = ""
var temp36 = ""
var temp37 = ""
var temp38 = ""
var temp39 = ""
var temp40 = ""
var temp41 = ""
var temp42 = ""
var temp43 = ""
var temp44 = ""
var temp45 = ""
var temp46 = ""
var temp47 = ""
var temp48 = ""
var temp49 = ""
var temp50 = ""
var temp51 = ""
var temp52 = ""
var temp53 = ""
var temp54 = ""
var temp55 = ""
var temp56 = ""
var temp57 = ""
var temp58 = ""
var temp59 = ""
var temp60 = ""
var temp61 = ""
var temp62 = ""
var temp63 = ""
var temp64 = ""
var temp65 = ""
var temp66 = ""
var temp67 = ""
var temp68 = ""
var temp69 = ""
var temp70 = ""
var temp71 = ""
var temp72 = ""
var temp73 = ""
var temp74 = ""
var temp75 = ""
var temp76 = ""
var temp77 = ""
var temp78 = ""
var temp79 = ""
var temp80 = ""
var temp81 = ""
var temp82 = ""
var temp83 = ""
var temp84 = ""
var temp85 = ""
var temp86 = ""
var temp87 = ""
var temp88 = ""
var temp89 = ""
var temp90 = ""
var temp91 = ""
var temp92 = ""
var temp93 = ""
var temp94 = ""
var temp95 = ""
var temp96 = ""
var temp97 = ""
var temp98 = ""
var temp99 = ""
var temp100 = ""
var temp101 = ""
var temp102 = ""
var temp103 = ""
var temp104 = ""
var temp105 = ""
var temp106 = ""
var temp107 = ""
var temp108 = ""
var temp109 = ""
var temp110 = ""
var temp111 = ""
var temp112 = ""
var temp113 = ""
var temp114 = ""
var temp115 = ""
var temp116 = ""
var temp117 = ""
var temp118 = ""
var temp119 = ""
var temp120 = ""
var temp121 = ""
var temp122 = ""
var temp123 = ""
var temp124 = ""
var temp125 = ""
var temp126 = ""
var temp127 = ""
var temp128 = ""
var temp129 = ""
var temp130 = ""
var temp131 = ""
var temp132 = ""
var temp133 = ""
var temp134 = ""
var temp135 = ""
var temp136 = ""
var temp137 = ""
var temp138 = ""
var temp139 = ""
var temp140 = ""
var temp141 = ""
XCTAssertTrue(antiShuffle(s: "Hi") == "Hi") // cannot find 'antiShuffle' in scope
XCTAssertTrue(antiShuffle(s: "hello") == "ehllo") // cannot find 'antiShuffle' in scope
XCTAssertTrue(antiShuffle(s: "number") == "bemnru") // cannot find 'antiShuffle' in scope
XCTAssertTrue(antiShuffle(s: "abcd") == "abcd") // cannot find 'antiShuffle' in scope
XCTAssertTrue(antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor") // cannot find 'antiShuffle' in scope
XCTAssertTrue(antiShuffle(s: "") == "") // cannot find 'antiShuffle' in scope
XCTAssertTrue(antiShuffle(s: "Hi. My name is Mister Robot. How are you?") == ".Hi My aemn is Meirst .Rboot How aer ?ouy") // cannot find 'antiShuffle' in scope
func antiShuffle(s: String) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
var temp = ""
for char in word {
temp.append(char)
}
temp = temp.sorted()
result += temp
result += " "
}
return result
}
```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.components(separatedBy: " ")
var result = ""
for word in words {
var temp = ""
for char in word {
temp.append(char)
}
temp = temp.sorted()
result += temp
result += " "
}
return result
}
```
temp = temp.sorted() // cannot assign value of type '[String.Element]' (aka 'Array<Character>') to type 'String'
func antiShuffle(s: String) -> String {
// Write your code here.
var result = ""
var arr = s.components(separatedBy: " ")
for word in arr {
var temp = word.sorted()
result += String(temp) + " "
}
return result
}
```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 {
// Write your code here.
var result = ""
var arr = s.components(separatedBy: " ")
for word in arr {
var temp = word.sorted()
result += String(temp) + " "
}
return result
}
```
var arr = s.components(separatedBy: " ") // variable 'arr' was never mutated; consider changing to 'let' constant
var temp = word.sorted() // variable 'temp' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = word.sorted()
result += String(sortedWord)
}
return result
}
```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.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = word.sorted()
result += String(sortedWord)
}
return result
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
// Write your code here
var result = ""
var arr = s.components(separatedBy: " ")
for i in 0..<arr.count {
let str = arr[i]
var temp = ""
for j in 0..<str.count {
temp += String(str[str.index(str.startIndex, offsetBy: j)])
}
temp = temp.sorted()
result += temp
if i!= arr.count - 1 {
result += " "
}
}
return result
}
```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 {
// Write your code here
var result = ""
var arr = s.components(separatedBy: " ")
for i in 0..<arr.count {
let str = arr[i]
var temp = ""
for j in 0..<str.count {
temp += String(str[str.index(str.startIndex, offsetBy: j)])
}
temp = temp.sorted()
result += temp
if i!= arr.count - 1 {
result += " "
}
}
return result
}
```
temp = temp.sorted() // cannot assign value of type '[String.Element]' (aka 'Array<Character>') to type 'String'
if i!= arr.count - 1 { // '=' must have consistent whitespace on both sides
if i!= arr.count - 1 { // cannot force unwrap value of non-optional type 'Int'
if i!= arr.count - 1 { // use of '=' in a boolean context, did you mean '=='?
func antiShuffle(s: String) -> String {
var result = ""
for char in s {
result += String(char).sorted()
}
return result
}
```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 = ""
for char in s {
result += String(char).sorted()
}
return result
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
var result = ""
var temp = ""
var temp2 = ""
for i in s {
if i == " " {
result += temp
result += temp2
temp = ""
temp2 = ""
} else {
temp += String(i)
temp2 += String(i)
}
}
result += temp
result += temp2
return result
}
```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 temp = ""
var temp2 = ""
for i in s {
if i == " " {
result += temp
result += temp2
temp = ""
temp2 = ""
} else {
temp += String(i)
temp2 += String(i)
}
}
result += temp
result += temp2
return result
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
return s
}
```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 {
return s
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = word.sorted()
result += String(sortedWord) + " "
}
return result.trimmingCharacters(in:.whitespaces)
}
```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.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = word.sorted()
result += String(sortedWord) + " "
}
return result.trimmingCharacters(in:.whitespaces)
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
// your code here
}
```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)] {
// your code here
}
```
} // missing return in global function expected to return '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (rowIndex, value) in row.enumerated() {
if value == x {
result.append((index, rowIndex))
}
}
}
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: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (rowIndex, value) in row.enumerated() {
if value == x {
result.append((index, rowIndex))
}
}
}
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (index2, value) in row.enumerated() {
if value == x {
result.append((index, index2))
}
}
}
return result.sorted { $0.0 < $1.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: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (index2, value) in row.enumerated() {
if value == x {
result.append((index, index2))
}
}
}
return result.sorted { $0.0 < $1.0 }
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return []
}
```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)] {
return []
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func sortArray(array: [Int]) -> [Int] {
let sum = array.reduce(0, +)
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.reduce(0, +)
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <)
}
```
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // cannot use optional chaining on non-optional value of type 'Int'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // result of call to 'sorted(by:)' is unused
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // expected expression
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // cannot convert return expression of type 'Bool' to return type '[Int]'
func sortArray(array: [Int]) -> [Int] {
let sum = array.reduce(0, +)
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.reduce(0, +)
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <)
}
```
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // cannot use optional chaining on non-optional value of type 'Int'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // result of call to 'sorted(by:)' is unused
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // expected expression
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // cannot convert return expression of type 'Bool' to return type '[Int]'
func sortArray(array: [Int]) -> [Int] {
let sum = array.reduce(0, +)
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.reduce(0, +)
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <)
}
```
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // cannot use optional chaining on non-optional value of type 'Int'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // result of call to 'sorted(by:)' is unused
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // expected expression
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? array.sorted(by: >) : array.sorted(by: <) // cannot convert return expression of type 'Bool' to return type '[Int]'
func sortArray(array: [Int]) -> [Int] {
var result = array
let sum = array.reduce(0, +)
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
let sum = array.reduce(0, +)
if sum % 2 == 0 {
result.sort(by: >)
} else {
result.sort(by: <)
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
let sum = array.reduce(0, +)
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
let sum = array.reduce(0, +)
if sum % 2 == 0 {
result.sort(by: >)
} else {
result.sort(by: <)
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
let sum = array.reduce(0, +)
if sum % 2 == 0 {
result.sort { $0 > $1 }
} else {
result.sort { $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
let sum = array.reduce(0, +)
if sum % 2 == 0 {
result.sort { $0 > $1 }
} else {
result.sort { $0 < $1 }
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
let sum = array.reduce(0, +)
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
let sum = array.reduce(0, +)
if sum % 2 == 0 {
result.sort(by: >)
} else {
result.sort(by: <)
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
if array.count > 1 {
let sum = array.first! + array.last!
if sum % 2 == 0 {
result.sort { $0 > $1 }
} else {
result.sort { $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 array.count > 1 {
let sum = array.first! + array.last!
if sum % 2 == 0 {
result.sort { $0 > $1 }
} else {
result.sort { $0 < $1 }
}
}
return result
}
```
func sortArray(array: [Int]) -> [Int] {
var result = array
if array.count <= 1 {
return result
}
let sum = array.first! + array.last!
if sum % 2 == 0 {
result.sort { $0 > $1 }
} else {
result.sort { $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 array.count <= 1 {
return result
}
let sum = array.first! + array.last!
if sum % 2 == 0 {
result.sort { $0 > $1 }
} else {
result.sort { $0 < $1 }
}
return result
}
```
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
encrypted.append(alphabet[newIndex - alphabet.count])
} else {
encrypted.append(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 {
var encrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
encrypted.append(alphabet[newIndex - alphabet.count])
} else {
encrypted.append(alphabet[newIndex])
}
}
}
return encrypted
}
```
if let index = alphabet.firstIndex(of: char) { // cannot find 'alphabet' in scope
if newIndex > alphabet.count - 1 { // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex - alphabet.count]) // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex - alphabet.count]) // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[newIndex])
}
}
}
return encryptedString
}
func decrypt(s: String) -> String {
var decryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index - 2
if newIndex < 0 {
let newIndex = newIndex + alphabet.count
decryptedString.append(alphabet[newIndex])
} else {
decryptedString.append(alphabet[newIndex])
}
}
}
return decryptedString
}
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[newIndex])
}
}
}
return encryptedString
}
func encryptDecrypt(s: String) -> String {
var decryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index - 2
if newIndex < 0 {
let newIndex = newIndex + alphabet.count
decryptedString.append(alphabet[newIndex])
} else {
decryptedString.append(alphabet[newIndex])
}
}
}
return decryptedString
}
```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 encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[newIndex])
}
}
}
return encryptedString
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var decryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index - 2
if newIndex < 0 {
let newIndex = newIndex + alphabet.count
decryptedString.append(alphabet[newIndex])
} else {
decryptedString.append(alphabet[newIndex])
}
}
}
return decryptedString
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et") == "ix"
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[newIndex])
}
}
}
return encryptedString
}
// Create a function encryptDecrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// encryptDecrypt(s: "lm") == "hi"
// encryptDecrypt(s: "ewhjklnop") == "asdfghjkl"
// encryptDecrypt(s: "kj") == "gf"
// encryptDecrypt(s: "ix") == "et"
func encryptDecrypt(s: String) -> String {
var decryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index - 2
if newIndex < 0 {
let newIndex = newIndex + alphabet.count
decryptedString.append(alphabet[newIndex])
} else {
decryptedString.append(alphabet[newIndex])
}
}
}
return decryptedString
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et") == "ix"
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[newIndex])
}
}
}
return encryptedString
}
// Create a function encryptDecrypt that
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
if newIndex > alphabet.count - 1 { // cannot find 'alphabet' in scope
let newIndex = newIndex - alphabet.count // cannot find 'alphabet' in scope
encryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
encryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
let newIndex = newIndex + alphabet.count // cannot find 'alphabet' in scope
decryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
decryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
if newIndex > alphabet.count - 1 { // cannot find 'alphabet' in scope
let newIndex = newIndex - alphabet.count // cannot find 'alphabet' in scope
encryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
encryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
func encryptDecrypt(s: String) -> String { // invalid redeclaration of 'encryptDecrypt(s:)'
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
let newIndex = newIndex + alphabet.count // cannot find 'alphabet' in scope
decryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
decryptedString.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var encrypted = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex >= alphabet.count {
encrypted.append(alphabet[newIndex - alphabet.count])
} else {
encrypted.append(alphabet[newIndex])
}
} else {
encrypted.append(letter)
}
}
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 {
var encrypted = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex >= alphabet.count {
encrypted.append(alphabet[newIndex - alphabet.count])
} else {
encrypted.append(alphabet[newIndex])
}
} else {
encrypted.append(letter)
}
}
return encrypted
}
```
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
if newIndex >= alphabet.count { // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex - alphabet.count]) // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex - alphabet.count]) // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 2
if newIndex >= alphabet.count {
encrypted.append(alphabet[newIndex - alphabet.count])
} else {
encrypted.append(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 {
var encrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 2
if newIndex >= alphabet.count {
encrypted.append(alphabet[newIndex - alphabet.count])
} else {
encrypted.append(alphabet[newIndex])
}
}
}
return encrypted
}
```
if let index = alphabet.firstIndex(of: char) { // cannot find 'alphabet' in scope
if newIndex >= alphabet.count { // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex - alphabet.count]) // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex - alphabet.count]) // cannot find 'alphabet' in scope
encrypted.append(alphabet[newIndex]) // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var result = ""
for char in s {
let index = char.unicodeScalars.first!.value
if index >= 97 && index <= 122 {
let newIndex = index + 2
result.append(Character(UnicodeScalar(newIndex)))
} else {
result.append(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 index = char.unicodeScalars.first!.value
if index >= 97 && index <= 122 {
let newIndex = index + 2
result.append(Character(UnicodeScalar(newIndex)))
} else {
result.append(char)
}
}
return result
}
```
result.append(Character(UnicodeScalar(newIndex))) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
func encrypt(s: String) -> String {
var encryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! + 2
if newIndex > 25 {
encryptedString += alphabet[newIndex - 26]
} else {
encryptedString += alphabet[newIndex]
}
}
return encryptedString
}
func decrypt(s: String) -> String {
var decryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! - 2
if newIndex < 0 {
decryptedString += alphabet[newIndex + 26]
} else {
decryptedString += alphabet[newIndex]
}
}
return decryptedString
}
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! + 2
if newIndex > 25 {
encryptedString += alphabet[newIndex - 26]
} else {
encryptedString += alphabet[newIndex]
}
}
return encryptedString
}
```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 encryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! + 2
if newIndex > 25 {
encryptedString += alphabet[newIndex - 26]
} else {
encryptedString += alphabet[newIndex]
}
}
return encryptedString
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var decryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! - 2
if newIndex < 0 {
decryptedString += alphabet[newIndex + 26]
} else {
decryptedString += alphabet[newIndex]
}
}
return decryptedString
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "lm") == "hi"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "ewhjklnop") == "asdfghjkl"
// encryptDecrypt(s: "kj") == "gf"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et") == "ix"
// encryptDecrypt(s: "ix") == "et"
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! + 2
if newIndex > 25 {
encryptedString += alphabet[newIndex - 26]
} else {
encryptedString += alphabet[newIndex]
}
}
return encryptedString
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "lm") == "hi"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "ewhjklnop") == "asdfghjkl"
// encryptDecrypt(s: "kj") == "gf"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et") == "ix"
// encryptDecrypt(s: "ix") == "et"
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for char in s {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = charIndex! + 2
if newIndex > 25 {
encryptedString += alphabet[newIndex - 26]
} else {
encryptedString += alphabet[newIndex]
}
}
return encryptedString
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "lm") == "hi"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "ewhjklnop") == "asdfghjkl"
// encryptDecrypt(s: "kj") == "gf"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et")
let charIndex = alphabet.firstIndex(of: char) // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex - 26] // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
let charIndex = alphabet.firstIndex(of: char) // cannot find 'alphabet' in scope
decryptedString += alphabet[newIndex + 26] // cannot find 'alphabet' in scope
decryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
let charIndex = alphabet.firstIndex(of: char) // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex - 26] // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
encrypted += alphabet[newIndex - alphabet.count]
} else {
encrypted += alphabet[newIndex]
}
}
}
return encrypted
}
func decrypt(s: String) -> String {
var decrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index - 2
if newIndex < 0 {
decrypted += alphabet[alphabet.count + newIndex]
} else {
decrypted += alphabet[newIndex]
}
}
}
return decrypted
}
```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 encrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
encrypted += alphabet[newIndex - alphabet.count]
} else {
encrypted += alphabet[newIndex]
}
}
}
return encrypted
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var decrypted = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index - 2
if newIndex < 0 {
decrypted += alphabet[alphabet.count + newIndex]
} else {
decrypted += alphabet[newIndex]
}
}
}
return decrypted
}
```
if let index = alphabet.firstIndex(of: char) { // cannot find 'alphabet' in scope
if newIndex > alphabet.count - 1 { // cannot find 'alphabet' in scope
encrypted += alphabet[newIndex - alphabet.count] // cannot find 'alphabet' in scope
encrypted += alphabet[newIndex - alphabet.count] // cannot find 'alphabet' in scope
encrypted += alphabet[newIndex] // cannot find 'alphabet' in scope
if let index = alphabet.firstIndex(of: char) { // cannot find 'alphabet' in scope
decrypted += alphabet[alphabet.count + newIndex] // cannot find 'alphabet' in scope
decrypted += alphabet[alphabet.count + newIndex] // cannot find 'alphabet' in scope
decrypted += alphabet[newIndex] // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString += alphabet[newIndex]
} else {
encryptedString += alphabet[newIndex]
}
}
}
return encryptedString
}
func decrypt(s: String) -> String {
var decryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index - 2
if newIndex < 0 {
let newIndex = newIndex + alphabet.count
decryptedString += alphabet[newIndex]
} else {
decryptedString += alphabet[newIndex]
}
}
}
return decryptedString
}
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString += alphabet[newIndex]
} else {
encryptedString += alphabet[newIndex]
}
}
}
return encryptedString
}
```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 encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString += alphabet[newIndex]
} else {
encryptedString += alphabet[newIndex]
}
}
}
return encryptedString
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var decryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index - 2
if newIndex < 0 {
let newIndex = newIndex + alphabet.count
decryptedString += alphabet[newIndex]
} else {
decryptedString += alphabet[newIndex]
}
}
}
return decryptedString
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et") == "ix"
func encryptDecrypt(s: String) -> String {
var encryptedString = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = index + 2
if newIndex > alphabet.count - 1 {
let newIndex = newIndex - alphabet.count
encryptedString += alphabet[newIndex]
} else {
encryptedString += alphabet[newIndex]
}
}
}
return encryptedString
}
```
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
if newIndex > alphabet.count - 1 { // cannot find 'alphabet' in scope
let newIndex = newIndex - alphabet.count // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
let newIndex = newIndex + alphabet.count // cannot find 'alphabet' in scope
decryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
decryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
if let index = alphabet.firstIndex(of: letter) { // cannot find 'alphabet' in scope
if newIndex > alphabet.count - 1 { // cannot find 'alphabet' in scope
let newIndex = newIndex - alphabet.count // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
encryptedString += alphabet[newIndex] // cannot find 'alphabet' in scope
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
let charIndex = Int(char.asciiValue!) - 97
let newIndex = (charIndex + 4) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
encrypted.append(newChar)
}
return encrypted
}
func decrypt(s: String) -> String {
var decrypted = ""
for char in s {
let charIndex = Int(char.asciiValue!) - 97
let newIndex = (charIndex + 22) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
decrypted.append(newChar)
}
return decrypted
}
func encryptDecrypt(s: String) -> String {
var encrypted = ""
for char in s {
let charIndex = Int(char.asciiValue!) - 97
let newIndex = (charIndex + 4) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
encrypted.append(newChar)
}
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 {
var encrypted = ""
for char in s {
let charIndex = Int(char.asciiValue!) - 97
let newIndex = (charIndex + 4) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
encrypted.append(newChar)
}
return encrypted
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var decrypted = ""
for char in s {
let charIndex = Int(char.asciiValue!) - 97
let newIndex = (charIndex + 22) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
decrypted.append(newChar)
}
return decrypted
}
// Create a function encryptDecrypt 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:
// encryptDecrypt(s: "hi") == "lm"
// encryptDecrypt(s: "asdfghjkl") == "ewhjklnop"
// encryptDecrypt(s: "gf") == "kj"
// encryptDecrypt(s: "et") == "ix"
// encryptDecrypt(s: "lm") == "hi"
// encryptDecrypt(s: "ewhjklnop") == "asdfghjkl"
// encryptDecrypt(s: "kj") == "gf"
// encryptDecrypt(s: "ix") == "et"
func encryptDecrypt(s: String) -> String {
var encrypted = ""
for char in s {
let charIndex = Int(char.asciiValue!) - 97
let newIndex = (charIndex + 4) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
encrypted.append(newChar)
}
return encrypted
}
```
func encrypt(s: String) -> String {
var encryptedString = ""
for char in s {
let charCode = char.asciiValue!
let encryptedCharCode = charCode + 2
let encryptedChar = Character(UnicodeScalar(encryptedCharCode))
encryptedString.append(encryptedChar)
}
return encryptedString
}
func decrypt(s: String) -> String {
var decryptedString = ""
for char in s {
let charCode = char.asciiValue!
let decryptedCharCode = charCode - 2
let decryptedChar = Character(UnicodeScalar(decryptedCharCode))
decryptedString.append(decryptedChar)
}
return decryptedString
}
```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 encryptedString = ""
for char in s {
let charCode = char.asciiValue!
let encryptedCharCode = charCode + 2
let encryptedChar = Character(UnicodeScalar(encryptedCharCode))
encryptedString.append(encryptedChar)
}
return encryptedString
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var decryptedString = ""
for char in s {
let charCode = char.asciiValue!
let decryptedCharCode = charCode - 2
let decryptedChar = Character(UnicodeScalar(decryptedCharCode))
decryptedString.append(decryptedChar)
}
return decryptedString
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var result: Int?
var min = Int.max
var min2 = Int.max
for i in lst {
if i < min {
min2 = min
min = i
} else if i < min2 {
min2 = i
}
}
if min2!= Int.max {
result = min2
}
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? {
var result: Int?
var min = Int.max
var min2 = Int.max
for i in lst {
if i < min {
min2 = min
min = i
} else if i < min2 {
min2 = i
}
}
if min2!= Int.max {
result = min2
}
return result
}
```
if min2!= Int.max { // '=' must have consistent whitespace on both sides
if min2!= Int.max { // cannot force unwrap value of non-optional type 'Int'
if min2!= Int.max { // use of '=' in a boolean context, did you mean '=='?
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
var smallest = sorted[0]
var secondSmallest: Int?
for i in 1..<sorted.count {
if sorted[i]!= smallest {
secondSmallest = sorted[i]
break
}
}
return secondSmallest
}
```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? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
var smallest = sorted[0]
var secondSmallest: Int?
for i in 1..<sorted.count {
if sorted[i]!= smallest {
secondSmallest = sorted[i]
break
}
}
return secondSmallest
}
```
if sorted[i]!= smallest { // '=' must have consistent whitespace on both sides
if sorted[i]!= smallest { // cannot force unwrap value of non-optional type 'Int'
if sorted[i]!= smallest { // use of '=' in a boolean context, did you mean '=='?
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let first = sorted.removeFirst()
let second = sorted.removeFirst()
return second
}
```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? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let first = sorted.removeFirst()
let second = sorted.removeFirst()
return second
}
```
let first = sorted.removeFirst() // initialization of immutable value 'first' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var sorted = lst.sorted()
if sorted.count < 2 {
return nil
}
return sorted[1]
}
```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? {
var sorted = lst.sorted()
if sorted.count < 2 {
return nil
}
return sorted[1]
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var smallest = lst[0]
var secondSmallest = lst[1]
for i in 2..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```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? {
guard lst.count > 1 else { return nil }
var smallest = lst[0]
var secondSmallest = lst[1]
for i in 2..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var smallest = lst[0]
var secondSmallest = lst[1]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```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? {
guard lst.count > 1 else { return nil }
var smallest = lst[0]
var secondSmallest = lst[1]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```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? {
guard lst.count > 1 else { return nil }
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let first = sorted.removeFirst()
let second = sorted.removeFirst()
return second
}
```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? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let first = sorted.removeFirst()
let second = sorted.removeFirst()
return second
}
```
let first = sorted.removeFirst() // initialization of immutable value 'first' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let first = sorted.removeFirst()
let second = sorted.removeFirst()
return second
}
```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? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let first = sorted.removeFirst()
let second = sorted.removeFirst()
return second
}
```
let first = sorted.removeFirst() // initialization of immutable value 'first' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let smallest = sorted.removeFirst()
return sorted.first
}
```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? {
guard lst.count > 1 else { return nil }
var sorted = lst.sorted()
let smallest = sorted.removeFirst()
return sorted.first
}
```
let smallest = sorted.removeFirst() // initialization of immutable value 'smallest' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".?!")
return words.filter { $0.hasPrefix("I") }.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.components(separatedBy: ".?!")
return words.filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".?!")
return words.filter { $0.hasPrefix("I") }.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.components(separatedBy: ".?!")
return words.filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredom = 0
for word in words {
if word.lowercased().hasPrefix("i") {
boredom += 1
}
}
return boredom
}
```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.components(separatedBy: " ")
var boredom = 0
for word in words {
if word.lowercased().hasPrefix("i") {
boredom += 1
}
}
return boredom
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredom = 0
for word in words {
if word.lowercased() == "i" {
boredom += 1
}
}
return boredom
}
```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.components(separatedBy: " ")
var boredom = 0
for word in words {
if word.lowercased() == "i" {
boredom += 1
}
}
return boredom
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredoms = 0
for word in words {
if word.lowercased() == "i" {
boredoms += 1
}
}
return boredoms
}
```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.components(separatedBy: " ")
var boredoms = 0
for word in words {
if word.lowercased() == "i" {
boredoms += 1
}
}
return boredoms
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredoms = 0
for word in words {
if word.lowercased().hasPrefix("i") {
boredoms += 1
}
}
return boredoms
}
```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.components(separatedBy: " ")
var boredoms = 0
for word in words {
if word.lowercased().hasPrefix("i") {
boredoms += 1
}
}
return boredoms
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".?!")
let bored = words.filter { $0.lowercased().hasPrefix("i") }
return bored.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.components(separatedBy: ".?!")
let bored = words.filter { $0.lowercased().hasPrefix("i") }
return bored.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".?!")
let bored = words.filter { $0.lowercased().hasPrefix("i") }
return bored.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.components(separatedBy: ".?!")
let bored = words.filter { $0.lowercased().hasPrefix("i") }
return bored.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredoms = 0
for word in words {
if word.lowercased() == "i" {
boredoms += 1
}
}
return boredoms
}
```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.components(separatedBy: " ")
var boredoms = 0
for word in words {
if word.lowercased() == "i" {
boredoms += 1
}
}
return boredoms
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".?!")
return words.filter { $0.lowercased().hasPrefix("i ") }.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.components(separatedBy: ".?!")
return words.filter { $0.lowercased().hasPrefix("i ") }.count
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x + y == z || x + z == y || y + z == x {
return true
}
}
return false
}
func isMultipleOf13(x: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 13) == 0 || x.truncatingRemainder(dividingBy: 13) == 1 {
return true
}
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 x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x + y == z || x + z == y || y + z == x {
return true
}
}
return false
}
// Create a function that takes a number.
// Returns true if the number is a multiple of 13 or if it is one higher of 13.
// Returns false in any other cases.
// Examples
// isMultipleOf13(x: 13) == true
// isMultipleOf13(x: 14) == false
// isMultipleOf13(x: 15) == true
// isMultipleOf13(x: 16) == false
func isMultipleOf13(x: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 13) == 0 || x.truncatingRemainder(dividingBy: 13) == 1 {
return true
}
return false
}
// Create a function that takes a number.
// Returns true if the number is a multiple of 13 or if it is one higher of 13.
// Returns false in any other cases.
// Examples
// isMultipleOf13(x: 13) == true
// isMultipleOf13(x: 14) == false
// isMultipleOf13(x: 15) == true
// isMultipleOf13(x: 16) == false
func isMultipleOf13(x: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 13) == 0 || x.truncatingRemainder(dividingBy: 13) == 1 {
return true
}
return false
}
// Create a function that takes a number.
// Returns true if the number is a multiple of 13 or if it is one higher of 13.
// Returns false in any other cases.
// Examples
// isMultipleOf13(x: 13) == true
// isMultipleOf13(x: 14) == false
// isMultipleOf13(x: 15) == true
// isMultipleOf13(x: 16) == false
func isMultipleOf13(x: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 13) == 0 || x.truncatingRemainder(dividingBy: 13) == 1 {
return true
}
return false
}
// Create a function that takes a number.
// Returns true if the number is a multiple of 13 or if it is one higher of 13.
// Returns false in any other cases.
// Examples
// isMultipleOf13(x: 13) == true
// isMultipleOf13(x: 14) == false
// isMultipleOf13(x: 15) == true
// isMultipleOf13(x: 16) == false
func isMultipleOf13(x: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 13) == 0 || x.truncatingRemainder(dividingBy: 13) == 1 {
return true
}
return false
}
// Create a function that takes a number.
// Returns true if the number is a multiple of 13 or if it is one higher of 13.
// Returns false in any other cases.
// Examples
// isMultipleOf13(x: 13) == true
// isMultipleOf13(x: 14) == false
// isMultipleOf13(x: 15) == true
// isMultipleOf13(x: 16) == false
func isMultipleOf13(x: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 13) == 0 || x.truncatingRemainder(dividingBy: 13) == 1 {
return true
}
return false
}
// Create a function that takes a number.
// Returns true if the number is a multiple of 13 or if it is one higher of 13.
// Returns false in any other cases.
// Examples
// is
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x == y + z || x == y - z || x == z - y {
return true
} else if y == x + z || y == x - z || y == z - x {
return true
} else if z == x + y || z == x - y || z == y - x {
return true
}
}
return false
}
func containsCode(str: String) -> Bool {
if str.contains("code") {
return true
}
return false
}
func containsCode(str: String) -> Bool {
if str.lowercased().contains("code") {
return true
}
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 x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x == y + z || x == y - z || x == z - y {
return true
} else if y == x + z || y == x - z || y == z - x {
return true
} else if z == x + y || z == x - y || z == y - x {
return true
}
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code".
// Examples
// containsCode("code") == true
// containsCode("Code") == true
// containsCode("Coding") == false
func containsCode(str: String) -> Bool {
if str.contains("code") {
return true
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code" as a substring.
// Examples
// containsCode("code") == true
// containsCode("Code") == true
// containsCode("Coding") == true
// containsCode("Codey") == false
func containsCode(str: String) -> Bool {
if str.contains("code") {
return true
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code" as a substring.
// Ignore the case of the string.
// Examples
// containsCode("code") == true
// containsCode("Code") == true
// containsCode("Coding") == true
// containsCode("Codey") == false
func containsCode(str: String) -> Bool {
if str.lowercased().contains("code") {
return true
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code" as a substring.
// Ignore the case of the string.
// If "code" appears more than once, return true.
// Examples
// containsCode("code") == true
// containsCode("Code") == true
// containsCode("Coding") == true
// containsCode("Codey") == false
// containsCode("Code Code Code") == true
func containsCode(str: String) -> Bool {
if str.lowercased().contains("code") {
return true
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code" as a substring.
// Ignore the case of the string.
// If "code" appears more than once, return true.
// If "code" appears at the beginning or end of the string, return true.
// Examples
// containsCode("code") == true
// containsCode("Code") == true
// containsCode("Coding") == true
// containsCode("Codey") == false
// containsCode("Code Code Code") == true
// containsCode("Code Code Code Code") == true
func containsCode(str: String) -> Bool {
if str.lowercased().contains("code") {
return true
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code" as a substring.
// Ignore the case of the string.
// If "code" appears more than once, return true.
// If "code" appears at the beginning or end of the string, return true.
// If "code" appears in the middle of the string, return false.
// Examples
// containsCode("code") == true
// containsCode("Code") == true
// containsCode("Coding") == true
// containsCode("Codey") == false
// containsCode("Code Code Code") == true
// containsCode("Code Code Code Code") == true
// containsCode("Code Code Code Code Code") == false
func containsCode(str: String) -> Bool {
if str.lowercased().contains("code") {
return true
}
return false
}
// Create a function that takes a string and returns true if the string contains the word "code" as a substring.
// Ignore the case of the string.
// If "code" appears more than once, return true.
// If "code" appears at the beginning or end of the string, return true.
// If "code" appears in the middle of the string, return false.
// If "code" appears in the middle of the string, but it is sur
func containsCode(str: String) -> Bool { // invalid redeclaration of 'containsCode(str:)'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x + y == z || x + z == y || y + z == x {
return true
} else {
return false
}
} else {
return false
}
}
func anyInt(x: Int, y: Int, z: Int) -> Bool {
if x + y == z || x + z == y || y + z == x {
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 x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x + y == z || x + z == y || y + z == x {
return true
} else {
return false
}
} else {
return false
}
}
// 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: Int, y: Int, z: Int) -> Bool {
if x + y == z || x + z == y || y + z == x {
return true
} else {
return false
}
}
```
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x == y + z || x == z + y || y == x + z || y == z + x || z == x + y || z == y + x {
return true
} else {
return false
}
} 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 x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0 {
if x == y + z || x == z + y || y == x + z || y == z + x || z == x + y || z == y + x {
return true
} else {
return false
}
} else {
return false
}
}
```
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encodedMessage = ""
for letter in message {
if letter.isUppercase {
encodedMessage.append(letter.lowercased())
} else if letter.isLowercase {
encodedMessage.append(letter.uppercased())
} else {
encodedMessage.append(letter)
}
}
return encodedMessage
}
```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 encodedMessage = ""
for letter in message {
if letter.isUppercase {
encodedMessage.append(letter.lowercased())
} else if letter.isLowercase {
encodedMessage.append(letter.uppercased())
} else {
encodedMessage.append(letter)
}
}
return encodedMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
} else {
encodedMessage += String(char)
}
}
return encodedMessage
}
```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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
} else {
encodedMessage += String(char)
}
}
return encodedMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
} else {
encodedMessage += String(char)
}
}
return encodedMessage
}
```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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
} else {
encodedMessage += String(char)
}
}
return encodedMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
} else {
encodedMessage += String(char)
}
}
return encodedMessage
}
```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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
} else {
encodedMessage += String(char)
}
}
return encodedMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value + 32)!))
} else {
encoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value + 32)!))
}
} else {
encoded.append(char)
}
}
return encoded
}
func decode(message: String) -> String {
var decoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
decoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value - 32)!))
} else {
decoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value - 32)!))
}
} else {
decoded.append(char)
}
}
return decoded
}
```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 encoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value + 32)!))
} else {
encoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value + 32)!))
}
} else {
encoded.append(char)
}
}
return encoded
}
// 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:
// decode(message: "TGST") == "test"
// decode(message: "tHKS KS C MGSSCGG") == "This is a message"
func decode(message: String) -> String {
var decoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
decoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value - 32)!))
} else {
decoded.append(Character(UnicodeScalar(char.unicodeScalars.first!.value - 32)!))
}
} else {
decoded.append(char)
}
}
return decoded
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encoded += String(char).lowercased()
} else {
encoded += String(char).uppercased()
}
} else {
encoded += String(char)
}
}
return encoded
}
```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 encoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encoded += String(char).lowercased()
} else {
encoded += String(char).uppercased()
}
} else {
encoded += String(char)
}
}
return encoded
}
// 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 encoded = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encoded += String(char).lowercased()
} else {
encoded += String(char).uppercased()
}
} else {
encoded += String(char)
}
}
return encoded
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage.append(String(char).lowercased())
} else {
encodedMessage.append(String(char).uppercased())
}
} else {
encodedMessage.append(char)
}
}
return encodedMessage
}
```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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage.append(String(char).lowercased())
} else {
encodedMessage.append(String(char).uppercased())
}
} else {
encodedMessage.append(char)
}
}
return encodedMessage
}
// 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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage.append(String(char).lowercased())
} else {
encodedMessage.append(String(char).uppercased())
}
} else {
encodedMessage.append(char)
}
}
return encodedMessage
}
// 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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage.append(String(char).lowercased())
} else {
encodedMessage.append(String(char).uppercased())
}
} else {
encodedMessage.append(char)
}
}
return encodedMessage
}
// 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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage.append(String(char).lowercased())
} else {
encodedMessage.append(String(char).uppercased())
}
} else {
encodedMessage.append(char)
}
}
return encodedMessage
}
// 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 encodedMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
encodedMessage.append(String(char).lowercased())
} else {
encodedMessage.append(String(char).uppercased())
}
} else {
encodedMessage.append(char)
}
}
return encodedMessage
}
// 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
// XCTAssertTrue failed
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isLetter {
if char.isUppercase {
result.append(char.lowercased())
} else {
result.append(char.uppercased())
}
} else {
result.append(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.isLetter {
if char.isUppercase {
result.append(char.lowercased())
} else {
result.append(char.uppercased())
}
} else {
result.append(char)
}
}
return result
}
// 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.isLetter {
if char.isUppercase {
result.append(char.lowercased())
} else {
result.append(char.uppercased())
}
} else {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isLetter {
if char.isUppercase {
result += String(char).lowercased()
} else {
result += String(char).uppercased()
}
} 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.isLetter {
if char.isUppercase {
result += String(char).lowercased()
} else {
result += String(char).uppercased()
}
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isLetter {
if char.isUppercase {
result.append(String(char).lowercased())
} else {
result.append(String(char).uppercased())
}
} else {
result.append(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.isLetter {
if char.isUppercase {
result.append(String(char).lowercased())
} else {
result.append(String(char).uppercased())
}
} else {
result.append(char)
}
}
return result
}
// 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.isLetter {
if char.isUppercase {
result.append(String(char).lowercased())
} else {
result.append(String(char).uppercased())
}
} else {
result.append(char)
}
}
return result
}
// 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.isLetter {
if char.isUppercase {
result.append(String(char).lowercased())
} else {
result.append(String(char).uppercased())
}
} else {
result.append(char)
}
}
return result
}
// 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.isLetter {
if char.isUppercase {
result.append(String(char).lowercased())
} else {
result.append(String(char).uppercased())
}
} else {
result.append(char)
}
}
return result
}
// 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.isLetter {
if char.isUppercase {
result.append(String(char).lowercased())
} else {
result.append(String(char).uppercased())
}
} else {
result.append(char)
}
}
return result
}
// 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.isLetter {
if char.isUpper
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var result = 0
for i in lst {
if i > 1 {
var j = 2
while i % j!= 0 {
j += 1
}
if j == i {
result += j
}
}
}
return result
}
```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 result = 0
for i in lst {
if i > 1 {
var j = 2
while i % j!= 0 {
j += 1
}
if j == i {
result += j
}
}
}
return result
}
```
while i % j!= 0 { // '=' must have consistent whitespace on both sides
while i % j!= 0 { // cannot force unwrap value of non-optional type 'Int'
while i % j!= 0 { // use of '=' in a boolean context, did you mean '=='?
func skjkasdkd(lst: [Int]) -> Int {
var result = 0
for i in lst {
if i > 1 {
var j = 2
while j * j <= i {
if i % j == 0 {
i /= j
j = 2
} else {
j += 1
}
}
if i > 1 {
result += i
}
}
}
return result
}
```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 result = 0
for i in lst {
if i > 1 {
var j = 2
while j * j <= i {
if i % j == 0 {
i /= j
j = 2
} else {
j += 1
}
}
if i > 1 {
result += i
}
}
}
return result
}
```
i /= j // left side of mutating operator isn't mutable: 'i' is a 'let' constant
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
return max.digits.reduce(0, +)
}
```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 max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
return max.digits.reduce(0, +)
}
```
if i > max && isPrime(i) { // cannot find 'isPrime' in scope
return max.digits.reduce(0, +) // value of type 'Int' has no member 'digits'
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
var sum = 0
for i in lst {
if i > max {
max = i
}
}
var str = String(max)
for i in str {
sum += Int(String(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 max = 0
var sum = 0
for i in lst {
if i > max {
max = i
}
}
var str = String(max)
for i in str {
sum += Int(String(i))!
}
return sum
}
```
var str = String(max) // variable 'str' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```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 max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var maxPrime = 0
for i in 2...max {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
if i > maxPrime {
maxPrime = i
}
}
}
var sum = 0
for i in String(maxPrime) {
sum += Int(String(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 max = 0
for i in lst {
if i > max {
max = i
}
}
var maxPrime = 0
for i in 2...max {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
if i > maxPrime {
maxPrime = i
}
}
}
var sum = 0
for i in String(maxPrime) {
sum += Int(String(i))!
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var maxStr = String(max)
var sum = 0
for i in maxStr {
sum += Int(String(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 max = 0
for i in lst {
if i > max {
max = i
}
}
var maxStr = String(max)
var sum = 0
for i in maxStr {
sum += Int(String(i))!
}
return sum
}
```
var maxStr = String(max) // variable 'maxStr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```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 max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var maxPrime = 0
var maxPrimeDigits = 0
for i in 2...max {
if max % i == 0 {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
}
}
if isPrime {
if i > maxPrime {
maxPrime = i
maxPrimeDigits = 0
for j in String(i) {
maxPrimeDigits += Int(String(j))!
}
}
}
}
}
return maxPrimeDigits
}
```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 max = 0
for i in lst {
if i > max {
max = i
}
}
var maxPrime = 0
var maxPrimeDigits = 0
for i in 2...max {
if max % i == 0 {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
}
}
if isPrime {
if i > maxPrime {
maxPrime = i
maxPrimeDigits = 0
for j in String(i) {
maxPrimeDigits += Int(String(j))!
}
}
}
}
}
return maxPrimeDigits
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```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 max = 0
for i in lst {
if i > max && isPrime(i) {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var count = 0
for i in 2...n {
if isPrime(i) {
result.append(i)
count += 1
}
if count == n {
break
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(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 = [Int]()
var count = 0
for i in 2...n {
if isPrime(i) {
result.append(i)
count += 1
}
if count == n {
break
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(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 = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[Int]'
func countUpTo(n: Int) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i < n {
if isPrime(i) {
result.append(i)
}
i += 1
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
var i = 2
while i < n {
if n % i == 0 {
return false
}
i += 1
}
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 = [Int]()
var i = 2
while i < n {
if isPrime(i) {
result.append(i)
}
i += 1
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
var i = 2
while i < n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
var i = 2
while primes.count < n {
if isPrime(i) {
primes.append(i)
}
i += 1
}
return primes
}
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 primes = [Int]()
var i = 2
while primes.count < n {
if isPrime(i) {
primes.append(i)
}
i += 1
}
return primes
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
for i in 2..<n {
if n % i == 0 { return false }
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
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 = [Int]()
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
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
if n > 0 {
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
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 = [Int]()
if n > 0 {
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
}
return result
}
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 countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...n-1 {
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: [Int] = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...n-1 {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
if n == 0 {
return result
}
for i in 2...n {
if isPrime(n: i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
if n == 2 {
return true
}
if n == 1 {
return false
}
for i in 2...n-1 {
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 = [Int]()
if n == 0 {
return result
}
for i in 2...n {
if isPrime(n: i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
if n == 2 {
return true
}
if n == 1 {
return false
}
for i in 2...n-1 {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return a * b
}
```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 a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return (a % 10) * (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 (a % 10) * (b % 10)
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return a * b
}
```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 a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return 0
}
```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 0
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase {
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 (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 {
if char.isUppercase {
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 (index, char) in s.enumerated() {
if index % 2 == 0 {
if char.isUppercase {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "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 (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
count += 1
}
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if i % 2 == 0, c.isUpper {
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, c) in s.enumerated() {
if i % 2 == 0, c.isUpper {
count += 1
}
}
return count
}
```
if i % 2 == 0, c.isUpper { // value of type 'String.Element' (aka 'Character') has no member 'isUpper'
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase {
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 (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "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 (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
count += 1
}
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "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 (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
count += 1
}
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "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 (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
count += 1
}
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase {
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 (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "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 (index, char) in s.enumerated() {
if index % 2 == 0 {
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
count += 1
}
}
}
return count
}
```
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let rounded = number.rounded(.awayFromZero)
return Int(rounded)
}
```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 = Double(value)?? 0
let rounded = number.rounded(.awayFromZero)
return Int(rounded)
}
```
let number = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let number = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let number = Double(value)?? 0 // integer literal is unused
let rounded = number.rounded(.awayFromZero) // cannot infer contextual base in reference to member 'awayFromZero'
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let rounded = Int(round(number))
return rounded
}
```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 = Double(value)?? 0
let rounded = Int(round(number))
return rounded
}
```
let number = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let number = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let number = Double(value)?? 0 // integer literal is unused
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let rounded = number.rounded(.awayFromZero)
return Int(rounded)
}
```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 = Double(value)?? 0
let rounded = number.rounded(.awayFromZero)
return Int(rounded)
}
```
let number = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let number = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let number = Double(value)?? 0 // integer literal is unused
let rounded = number.rounded(.awayFromZero) // cannot infer contextual base in reference to member 'awayFromZero'
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let rounded = Int(round(number))
return rounded
}
```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 = Double(value)?? 0
let rounded = Int(round(number))
return rounded
}
```
let number = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let number = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let number = Double(value)?? 0 // integer literal is unused
func closestInteger(value: String) -> Int {
let doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
let roundedIntValue = Int(roundedValue)
return roundedIntValue
}
```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 doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
let roundedIntValue = Int(roundedValue)
return roundedIntValue
}
```
let doubleValue = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let doubleValue = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let doubleValue = Double(value)?? 0 // integer literal is unused
func closestInteger(value: String) -> Int {
let doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
if roundedValue == doubleValue {
return Int(roundedValue)
} else {
return Int(doubleValue > 0? roundedValue + 1 : roundedValue - 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 doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
if roundedValue == doubleValue {
return Int(roundedValue)
} else {
return Int(doubleValue > 0? roundedValue + 1 : roundedValue - 1)
}
}
```
let doubleValue = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let doubleValue = Double(value)?? 0 // integer literal is unused
let doubleValue = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
return Int(doubleValue > 0? roundedValue + 1 : roundedValue - 1) // expected ',' separator
return Int(doubleValue > 0? roundedValue + 1 : roundedValue - 1) // cannot use optional chaining on non-optional value of type 'Int'
return Int(doubleValue > 0? roundedValue + 1 : roundedValue - 1) // no exact matches in call to initializer
return Int(doubleValue > 0? roundedValue + 1 : roundedValue - 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
let roundedIntValue = Int(roundedValue)
let roundedDoubleValue = Double(roundedIntValue)
let diff = abs(doubleValue - roundedDoubleValue)
if diff == 0.5 {
return roundedIntValue
} else if diff < 0.5 {
return roundedIntValue
} else {
return roundedIntValue + 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 doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
let roundedIntValue = Int(roundedValue)
let roundedDoubleValue = Double(roundedIntValue)
let diff = abs(doubleValue - roundedDoubleValue)
if diff == 0.5 {
return roundedIntValue
} else if diff < 0.5 {
return roundedIntValue
} else {
return roundedIntValue + 1
}
}
```
let doubleValue = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let doubleValue = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let doubleValue = Double(value)?? 0 // integer literal is unused
let diff = abs(doubleValue - roundedDoubleValue) // cannot convert value of type 'Duration' to expected argument type 'Int32'
func closestInteger(value: String) -> Int {
let doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
return Int(roundedValue)
}
```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 doubleValue = Double(value)?? 0
let roundedValue = round(doubleValue)
return Int(roundedValue)
}
```
let doubleValue = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let doubleValue = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let doubleValue = Double(value)?? 0 // integer literal is unused
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let rounded = number.rounded()
if rounded == number {
return Int(rounded)
} else {
return Int(number > rounded? rounded - 1 : rounded + 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 = Double(value)?? 0
let rounded = number.rounded()
if rounded == number {
return Int(rounded)
} else {
return Int(number > rounded? rounded - 1 : rounded + 1)
}
}
```
let number = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let number = Double(value)?? 0 // integer literal is unused
let number = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
return Int(number > rounded? rounded - 1 : rounded + 1) // no exact matches in call to initializer
return Int(number > rounded? rounded - 1 : rounded + 1) // expected ',' separator
return Int(number > rounded? rounded - 1 : rounded + 1) // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
func closestInteger(value: String) -> Int {
let doubleValue = Double(value)
let roundedValue = round(doubleValue!)
let roundedIntValue = Int(roundedValue)
return roundedIntValue
}
```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 doubleValue = Double(value)
let roundedValue = round(doubleValue!)
let roundedIntValue = Int(roundedValue)
return roundedIntValue
}
```
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 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]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 1
}
return pile
}
```
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // result of operator '+' is unused
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot assign value of type 'Bool' to type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // expected expression
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level / 2 : level + 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]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level / 2 : level + 1
}
return pile
}
```
level = level % 2 == 0? level / 2 : level + 1 // consecutive statements on a line must be separated by ';'
level = level % 2 == 0? level / 2 : level + 1 // expected expression
level = level % 2 == 0? level / 2 : level + 1 // cannot use optional chaining on non-optional value of type 'Int'
level = level % 2 == 0? level / 2 : level + 1 // consecutive statements on a line must be separated by ';'
level = level % 2 == 0? level / 2 : level + 1 // result of operator '/' is unused
level = level % 2 == 0? level / 2 : level + 1 // cannot assign value of type 'Bool' to type 'Int'
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level + 2 : level + 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]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level + 2 : level + 1
}
return pile
}
```
level = level % 2 == 0? level + 2 : level + 1 // cannot assign value of type 'Bool' to type 'Int'
level = level % 2 == 0? level + 2 : level + 1 // result of operator '+' is unused
level = level % 2 == 0? level + 2 : level + 1 // cannot use optional chaining on non-optional value of type 'Int'
level = level % 2 == 0? level + 2 : level + 1 // expected expression
level = level % 2 == 0? level + 2 : level + 1 // consecutive statements on a line must be separated by ';'
level = level % 2 == 0? level + 2 : level + 1 // consecutive statements on a line must be separated by ';'
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level + 2 : level + 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]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level + 2 : level + 1
}
return pile
}
```
level = level % 2 == 0? level + 2 : level + 1 // cannot assign value of type 'Bool' to type 'Int'
level = level % 2 == 0? level + 2 : level + 1 // result of operator '+' is unused
level = level % 2 == 0? level + 2 : level + 1 // cannot use optional chaining on non-optional value of type 'Int'
level = level % 2 == 0? level + 2 : level + 1 // expected expression
level = level % 2 == 0? level + 2 : level + 1 // consecutive statements on a line must be separated by ';'
level = level % 2 == 0? level + 2 : level + 1 // consecutive statements on a line must be separated by ';'
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 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]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 1
}
return pile
}
```
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // result of operator '+' is unused
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot assign value of type 'Bool' to type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // expected expression
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 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]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 1
}
return pile
}
```
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // result of operator '+' is unused
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot assign value of type 'Bool' to type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // expected expression
func makeAPile(n: Int) -> [Int] {
var pile = [n]
while n > 1 {
if n % 2 == 0 {
n -= 1
}
pile.append(n)
n -= 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 = [n]
while n > 1 {
if n % 2 == 0 {
n -= 1
}
pile.append(n)
n -= 1
}
return pile
}
```
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 makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 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]()
var stones = n
while stones > 0 {
pile.append(stones)
stones = stones % 2 == 0? stones + 2 : stones + 1
}
return pile
}
```
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones + 2 : stones + 1 // result of operator '+' is unused
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot assign value of type 'Bool' to type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones + 2 : stones + 1 // expected expression
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level + 2 : level + 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]()
var level = n
while level > 0 {
pile.append(level)
level = level % 2 == 0? level + 2 : level + 1
}
return pile
}
```
level = level % 2 == 0? level + 2 : level + 1 // cannot assign value of type 'Bool' to type 'Int'
level = level % 2 == 0? level + 2 : level + 1 // result of operator '+' is unused
level = level % 2 == 0? level + 2 : level + 1 // cannot use optional chaining on non-optional value of type 'Int'
level = level % 2 == 0? level + 2 : level + 1 // expected expression
level = level % 2 == 0? level + 2 : level + 1 // consecutive statements on a line must be separated by ';'
level = level % 2 == 0? level + 2 : level + 1 // consecutive statements on a line must be separated by ';'
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var stones = n
for _ in 0..<n {
pile.append(stones)
stones += stones % 2
}
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]()
var stones = n
for _ in 0..<n {
pile.append(stones)
stones += stones % 2
}
return pile
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```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.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// Your code goes here
}
```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 {
// Your code goes here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```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> {
guard n <= m else { return.failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
return.success(String(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> {
guard n <= m else { return.failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
return.success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
return.success(String(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> {
guard n <= m else { return.failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
return.success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return.success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```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> {
guard n <= m else { return.failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return.success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func uniqueDigits(x: [Int]) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func uniqueDigits(x: [Int]) -> [Int] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[Int]'
func uniqueDigits(x: [Int]) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
var isUnique = true
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
isUnique = false
break
}
temp /= 10
}
if isUnique {
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 {
var temp = i
var isUnique = true
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
isUnique = false
break
}
temp /= 10
}
if isUnique {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
var isUnique = true
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
isUnique = false
break
}
temp /= 10
}
if isUnique {
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 {
var temp = i
var isUnique = true
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
isUnique = false
break
}
temp /= 10
}
if isUnique {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result: [Int] = []
for num in x {
var num = num
var isUnique = true
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
isUnique = false
break
}
num /= 10
}
if isUnique {
result.append(num)
}
}
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 num in x {
var num = num
var isUnique = true
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
isUnique = false
break
}
num /= 10
}
if isUnique {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var num = num
var isUnique = true
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
isUnique = false
break
}
num /= 10
}
if isUnique {
result.append(num)
}
}
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 num in x {
var num = num
var isUnique = true
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
isUnique = false
break
}
num /= 10
}
if isUnique {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter {
$0.description.filter {
$0.isNumber
}.count == $0.description.count
}.sorted()
}
```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.description.filter {
$0.isNumber
}.count == $0.description.count
}.sorted()
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var num = i
var isUnique = true
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
isUnique = false
break
}
num /= 10
}
if isUnique {
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 {
var num = i
var isUnique = true
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
isUnique = false
break
}
num /= 10
}
if isUnique {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.description.filter { $0.isNumber }.count == $0.description.count }
}
```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.description.filter { $0.isNumber }.count == $0.description.count }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
}
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 = [String]()
for i in arr {
if i >= 1 && i <= 9 {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
}
result.reverse()
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
result.sort()
result.reverse()
for i in 0..<result.count {
switch result[i] {
case "1":
result[i] = "One"
case "2":
result[i] = "Two"
case "3":
result[i] = "Three"
case "4":
result[i] = "Four"
case "5":
result[i] = "Five"
case "6":
result[i] = "Six"
case "7":
result[i] = "Seven"
case "8":
result[i] = "Eight"
case "9":
result[i] = "Nine"
default:
break
}
}
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 = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
result.sort()
result.reverse()
for i in 0..<result.count {
switch result[i] {
case "1":
result[i] = "One"
case "2":
result[i] = "Two"
case "3":
result[i] = "Three"
case "4":
result[i] = "Four"
case "5":
result[i] = "Five"
case "6":
result[i] = "Six"
case "7":
result[i] = "Seven"
case "8":
result[i] = "Eight"
case "9":
result[i] = "Nine"
default:
break
}
}
return result
}
```
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for number in arr {
if number >= 1 && number <= 9 {
result.append(String(number))
}
}
result.sort()
result.reverse()
for (index, number) in result.enumerated() {
switch number {
case "1":
result[index] = "One"
case "2":
result[index] = "Two"
case "3":
result[index] = "Three"
case "4":
result[index] = "Four"
case "5":
result[index] = "Five"
case "6":
result[index] = "Six"
case "7":
result[index] = "Seven"
case "8":
result[index] = "Eight"
case "9":
result[index] = "Nine"
default:
break
}
}
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 = [String]()
for number in arr {
if number >= 1 && number <= 9 {
result.append(String(number))
}
}
result.sort()
result.reverse()
for (index, number) in result.enumerated() {
switch number {
case "1":
result[index] = "One"
case "2":
result[index] = "Two"
case "3":
result[index] = "Three"
case "4":
result[index] = "Four"
case "5":
result[index] = "Five"
case "6":
result[index] = "Six"
case "7":
result[index] = "Seven"
case "8":
result[index] = "Eight"
case "9":
result[index] = "Nine"
default:
break
}
}
return result
}
```
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for number in arr {
if number >= 1 && number <= 9 {
result.append(number.description)
}
}
result.sort()
result.reverse()
for (index, number) in result.enumerated() {
switch number {
case "1":
result[index] = "One"
case "2":
result[index] = "Two"
case "3":
result[index] = "Three"
case "4":
result[index] = "Four"
case "5":
result[index] = "Five"
case "6":
result[index] = "Six"
case "7":
result[index] = "Seven"
case "8":
result[index] = "Eight"
case "9":
result[index] = "Nine"
default:
break
}
}
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 = [String]()
for number in arr {
if number >= 1 && number <= 9 {
result.append(number.description)
}
}
result.sort()
result.reverse()
for (index, number) in result.enumerated() {
switch number {
case "1":
result[index] = "One"
case "2":
result[index] = "Two"
case "3":
result[index] = "Three"
case "4":
result[index] = "Four"
case "5":
result[index] = "Five"
case "6":
result[index] = "Six"
case "7":
result[index] = "Seven"
case "8":
result[index] = "Eight"
case "9":
result[index] = "Nine"
default:
break
}
}
return result
}
```
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
}
return result.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] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
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 []
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i < 1 || i > 9 {
continue
}
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
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 = [String]()
for i in arr {
if i < 1 || i > 9 {
continue
}
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
result.reverse()
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
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 []
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
return arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed().map { names[$0 - 1] }
}
```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 names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
return arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed().map { names[$0 - 1] }
}
```
func byLength(arr: [Int]) -> [String] {
var result: [String] = []
for i in arr {
if i >= 1 && i <= 9 {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
}
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: [String] = []
for i in arr {
if i >= 1 && i <= 9 {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
}
result.reverse()
return result
}
```
// XCTAssertTrue failed
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(_ range: Range<Int>) -> Int {
var result = 0
for i in range {
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(_ range: Range<Int>) -> Int {
var result = 0
for i in range {
result += i
}
return result
}
```
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<Int>'
func f(n: Int) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[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(_ range: Range<Int>) -> Int {
return range.reduce(0, +)
}
```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(_ range: Range<Int>) -> Int {
return range.reduce(0, +)
}
```
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from start: Int, to 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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from start: Int, to end: Int) -> Int {
var result = 0
for i in start...end {
result += i
}
return result
}
```
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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from: Int, to: Int) -> Int {
var result = 0
for i in from...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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from: Int, to: Int) -> Int {
var result = 0
for i in from...to {
result += i
}
return result
}
```
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(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
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(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
guard n > 1 else { return 1 }
return n * factorial(n - 1)
}
func sum(from start: Int, to end: Int) -> Int {
guard start < end else { return 0 }
return start + sum(from: start + 1, to: end)
}
```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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
guard n > 1 else { return 1 }
return n * factorial(n - 1)
}
func sum(from start: Int, to end: Int) -> Int {
guard start < end else { return 0 }
return start + sum(from: start + 1, to: end)
}
```
// XCTAssertTrue failed
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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from: Int, to: Int) -> Int {
var result = 0
for i in from...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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from: Int, to: Int) -> Int {
var result = 0
for i in from...to {
result += i
}
return result
}
```
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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from start: Int, to 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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from start: Int, to end: Int) -> Int {
var result = 0
for i in start...end {
result += i
}
return result
}
```
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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from start: Int, to 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(from: 1, to: i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(from start: Int, to end: Int) -> Int {
var result = 0
for i in start...end {
result += i
}
return result
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if str == String(str.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 str = String(i)
if str == String(str.reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var n = n
var reversed = 0
while n > 0 {
reversed = reversed * 10 + n % 10
n /= 10
}
return reversed == n
}
```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 isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var n = n
var reversed = 0
while n > 0 {
reversed = reversed * 10 + n % 10
n /= 10
}
return reversed == n
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == 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(s.reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == 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(s.reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ num: Int) -> Bool {
var num = num
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return reversed == num
}
```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 isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ num: Int) -> Bool {
var num = num
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return reversed == num
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return n == reversed
}
```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 isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return n == reversed
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == 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(s.reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if str == String(str.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 str = String(i)
if str == String(str.reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ num: Int) -> Bool {
var num = num
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return reversed == num
}
```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 isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ num: Int) -> Bool {
var num = num
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return reversed == num
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if str == String(str.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 str = String(i)
if str == String(str.reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
func countNums(arr: [Int]) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { (result, num) -> Int in
var num = num
var sum = 0
while num!= 0 {
sum += abs(num % 10)
num /= 10
}
return result + (sum > 0? 1 : 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.reduce(0) { (result, num) -> Int in
var num = num
var sum = 0
while num!= 0 {
sum += abs(num % 10)
num /= 10
}
return result + (sum > 0? 1 : 0)
}
}
```
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
while num!= 0 { // '=' must have consistent whitespace on both sides
return result + (sum > 0? 1 : 0) // expected ',' separator
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { (result, num) -> Int in
var num = num
var sum = 0
while num!= 0 {
sum += num % 10
num /= 10
}
return result + (sum > 0? 1 : 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.reduce(0) { (result, num) -> Int in
var num = num
var sum = 0
while num!= 0 {
sum += num % 10
num /= 10
}
return result + (sum > 0? 1 : 0)
}
}
```
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
while num!= 0 { // '=' must have consistent whitespace on both sides
return result + (sum > 0? 1 : 0) // expected ',' separator
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 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 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var num = num
var sum = 0
while num!= 0 {
sum += num % 10
num /= 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 {
var num = num
var sum = 0
while num!= 0 {
sum += num % 10
num /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
while num!= 0 { // '=' must have consistent whitespace on both sides
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { (result, num) -> Int in
var num = num
var sum = 0
while num!= 0 {
sum += num % 10
num /= 10
}
return result + (sum > 0? 1 : 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.reduce(0) { (result, num) -> Int in
var num = num
var sum = 0
while num!= 0 {
sum += num % 10
num /= 10
}
return result + (sum > 0? 1 : 0)
}
}
```
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
while num!= 0 { // '=' must have consistent whitespace on both sides
return result + (sum > 0? 1 : 0) // expected ',' separator
func countNums(arr: [Int]) -> Int {
return arr.filter {
$0 > 0
}.reduce(0) {
$0 + 1
}
}
```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.filter {
$0 > 0
}.reduce(0) {
$0 + 1
}
}
```
}.reduce(0) { // contextual closure type '(Int, Int) throws -> Int' expects 2 arguments, but 1 was used in closure body
func countNums(arr: [Int]) -> Int {
return arr.filter { $0 > 0 }.reduce(0) { $0 + String($1).reduce(0) { $0 + $1.wholeNumberValue! } }
}
```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.filter { $0 > 0 }.reduce(0) { $0 + String($1).reduce(0) { $0 + $1.wholeNumberValue! } }
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { (result, num) -> Int in
let numStr = String(num)
let numArr = numStr.map { Int(String($0))! }
let sum = numArr.reduce(0, +)
if sum > 0 {
return result + 1
} else {
return result
}
}
}
```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.reduce(0) { (result, num) -> Int in
let numStr = String(num)
let numArr = numStr.map { Int(String($0))! }
let sum = numArr.reduce(0, +)
if sum > 0 {
return result + 1
} else {
return result
}
}
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func countNums(arr: [Int]) -> Int {
return arr.filter { $0 > 0 }.reduce(0) { $0 + String($1).compactMap { Int(String($0)) }.reduce(0, +) > 0? 1 : 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.filter { $0 > 0 }.reduce(0) { $0 + String($1).compactMap { Int(String($0)) }.reduce(0, +) > 0? 1 : 0 }
}
```
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 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 arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 1
}
return count <= 1
}
```
while arr!= arr.sorted() { // cannot force unwrap value of non-optional type '[Int]'
while arr!= arr.sorted() { // use of '=' in a boolean context, did you mean '=='?
while arr!= arr.sorted() { // '=' must have consistent whitespace on both sides
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 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 arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 1
}
return count <= 1
}
```
while arr!= arr.sorted() { // cannot force unwrap value of non-optional type '[Int]'
while arr!= arr.sorted() { // use of '=' in a boolean context, did you mean '=='?
while arr!= arr.sorted() { // '=' must have consistent whitespace on both sides
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 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
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
}
}
return count <= 1
}
```
// Fatal error: Range requires lowerBound <= upperBound
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 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 arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 1
}
return count <= 1
}
```
while arr!= arr.sorted() { // cannot force unwrap value of non-optional type '[Int]'
while arr!= arr.sorted() { // use of '=' in a boolean context, did you mean '=='?
while arr!= arr.sorted() { // '=' must have consistent whitespace on both sides
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 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 arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 1
}
return count <= 1
}
```
while arr!= arr.sorted() { // cannot force unwrap value of non-optional type '[Int]'
while arr!= arr.sorted() { // use of '=' in a boolean context, did you mean '=='?
while arr!= arr.sorted() { // '=' must have consistent whitespace on both sides
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 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 arr = arr
var count = 0
while arr!= arr.sorted() {
arr.append(arr.removeFirst())
count += 1
}
return count <= 1
}
```
while arr!= arr.sorted() { // cannot force unwrap value of non-optional type '[Int]'
while arr!= arr.sorted() { // use of '=' in a boolean context, did you mean '=='?
while arr!= arr.sorted() { // '=' must have consistent whitespace on both sides
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr.count > 1 {
if arr[0] > arr[1] {
arr.append(arr[0])
arr.remove(at: 0)
count += 1
} else {
arr.remove(at: 0)
}
}
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 arr = arr
var count = 0
while arr.count > 1 {
if arr[0] > arr[1] {
arr.append(arr[0])
arr.remove(at: 0)
count += 1
} else {
arr.remove(at: 0)
}
}
return count <= 1
}
```
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 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
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
}
}
return count <= 1
}
```
// Fatal error: Range requires lowerBound <= upperBound
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
while arr.count > 1 {
if arr[0] > arr[1] {
arr.append(arr[0])
arr.remove(at: 0)
count += 1
} else {
arr.insert(arr[arr.count - 1], at: 0)
arr.remove(at: arr.count - 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 arr = arr
var count = 0
while arr.count > 1 {
if arr[0] > arr[1] {
arr.append(arr[0])
arr.remove(at: 0)
count += 1
} else {
arr.insert(arr[arr.count - 1], at: 0)
arr.remove(at: arr.count - 1)
}
}
return count <= 1
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
for i in 0..<lst2.count {
if lst2[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 lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 0 {
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 lst1 = lst1
var lst2 = lst2
var result = "NO"
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
continue
}
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = 0
result = "YES"
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 lst1 = lst1
var lst2 = lst2
var result = "NO"
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
continue
}
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = 0
result = "YES"
break
}
}
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var result = "NO"
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
return result
}
}
}
if lst2.count == 0 {
result = "YES"
}
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 = "NO"
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
return result
}
}
}
if lst2.count == 0 {
result = "YES"
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
for i in 0..<lst2.count {
if lst2[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 lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 0 {
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 result = "NO"
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
break
}
}
}
if lst1.count == 0 {
result = "YES"
}
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 = "NO"
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
break
}
}
}
if lst1.count == 0 {
result = "YES"
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var result = "NO"
var even = 0
var odd = 0
for i in lst1 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
for i in lst2 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
if even == lst1.count && odd == lst2.count {
result = "YES"
}
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 = "NO"
var even = 0
var odd = 0
for i in lst1 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
for i in lst2 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
if even == lst1.count && odd == lst2.count {
result = "YES"
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 1 {
count += 1
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 1 {
count += 1
}
}
if count % 2 == 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 0..<lst1.count {
if lst1[i] % 2 == 1 {
count += 1
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 1 {
count += 1
}
}
if count % 2 == 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 result = "NO"
var count = 0
var count2 = 0
for i in lst1 {
if i % 2 == 0 {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
count2 += 1
}
}
if count == lst1.count && count2 == lst2.count {
result = "YES"
}
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 = "NO"
var count = 0
var count2 = 0
for i in lst1 {
if i % 2 == 0 {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
count2 += 1
}
}
if count == lst1.count && count2 == lst2.count {
result = "YES"
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
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 {
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
return "NO"
}
}
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
return "NO"
}
}
}
if lst2.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
while lst1.count > 0 {
if lst1[0] % 2 == 0 {
lst1.remove(at: 0)
} else {
if lst2.count > 0 {
lst1.remove(at: 0)
lst2.remove(at: 0)
count += 1
} else {
return "NO"
}
}
}
if lst2.count == 0 {
return "YES"
} else {
return "NO"
}
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word]!= nil {
result[word]! += 1
} else {
result[word] = 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word]!= nil {
result[word]! += 1
} else {
result[word] = 1
}
}
return result
}
```
if result[word]!= nil { // use of '=' in a boolean context, did you mean '=='?
if result[word]!= nil { // 'nil' cannot be assigned to type 'Int'
if result[word]!= nil { // '=' must have consistent whitespace on both sides
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word]!= nil {
result[word]! += 1
} else {
result[word] = 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word]!= nil {
result[word]! += 1
} else {
result[word] = 1
}
}
return result
}
```
if result[word]!= nil { // use of '=' in a boolean context, did you mean '=='?
if result[word]!= nil { // 'nil' cannot be assigned to type 'Int'
if result[word]!= nil { // '=' must have consistent whitespace on both sides
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
var words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```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 result = [String : Int]()
var words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```
var words = test.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word]!= nil {
result[word]! += 1
} else {
result[word] = 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word]!= nil {
result[word]! += 1
} else {
result[word] = 1
}
}
return result
}
```
if result[word]!= nil { // use of '=' in a boolean context, did you mean '=='?
if result[word]!= nil { // 'nil' cannot be assigned to type 'Int'
if result[word]!= nil { // '=' must have consistent whitespace on both sides
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if dict[word]!= nil {
dict[word]! += 1
} else {
dict[word] = 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]()
let words = test.components(separatedBy: " ")
for word in words {
if dict[word]!= nil {
dict[word]! += 1
} else {
dict[word] = 1
}
}
return dict
}
```
if dict[word]!= nil { // '=' must have consistent whitespace on both sides
if dict[word]!= nil { // use of '=' in a boolean context, did you mean '=='?
if dict[word]!= nil { // 'nil' cannot be assigned to type 'Int'
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
var letters = test.components(separatedBy: " ")
for letter in letters {
if result[letter] == nil {
result[letter] = 1
} else {
result[letter]! += 1
}
}
return result
}
```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 result = [String : Int]()
var letters = test.components(separatedBy: " ")
for letter in letters {
if result[letter] == nil {
result[letter] = 1
} else {
result[letter]! += 1
}
}
return result
}
```
var letters = test.components(separatedBy: " ") // variable 'letters' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```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 result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if result[word] == nil {
result[word] = 1
} else {
result[word]! += 1
}
}
return result
}
```
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (String(result.reversed()), 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.append(char)
} else {
isPalindrome = false
}
}
return (String(result.reversed()), isPalindrome)
}
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = false
for char in s {
if!c.contains(char) {
result.append(char)
}
}
if result.reversed() == result {
isPalindrome = true
}
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 = false
for char in s {
if!c.contains(char) {
result.append(char)
}
}
if result.reversed() == result {
isPalindrome = true
}
return (result, isPalindrome)
}
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
if result.reversed() == result { // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = false
for char in s {
if!c.contains(char) {
result.append(char)
}
}
if String(result.reversed()) == result {
isPalindrome = true
}
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 = false
for char in s {
if!c.contains(char) {
result.append(char)
}
}
if String(result.reversed()) == result {
isPalindrome = true
}
return (result, isPalindrome)
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var cSet = Set(c)
for char in s {
if!cSet.contains(char) {
result.append(char)
}
}
return (result, result.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 = ""
var cSet = Set(c)
for char in s {
if!cSet.contains(char) {
result.append(char)
}
}
return (result, result.reversed() == result)
}
```
if!cSet.contains(char) { // expected expression, var, or let in 'if' condition
return (result, result.reversed() == result) // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
var set = Set<Character>()
for char in c {
set.insert(char)
}
for char in s {
if!set.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (String(result.reversed()), 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
var set = Set<Character>()
for char in c {
set.insert(char)
}
for char in s {
if!set.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (String(result.reversed()), isPalindrome)
}
```
if!set.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var cArr = Array(c)
var sArr = Array(s)
var i = 0
while i < sArr.count {
if cArr.contains(sArr[i]) {
sArr.remove(at: i)
} else {
result.append(sArr[i])
i += 1
}
}
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 = ""
var cArr = Array(c)
var sArr = Array(s)
var i = 0
while i < sArr.count {
if cArr.contains(sArr[i]) {
sArr.remove(at: i)
} else {
result.append(sArr[i])
i += 1
}
}
return (result, result == String(result.reversed()))
}
```
var cArr = Array(c) // variable 'cArr' was never mutated; consider changing to 'let' constant
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var set = Set<Character>()
for char in c {
set.insert(char)
}
for char in s {
if!set.contains(char) {
result.append(char)
}
}
return (result, result.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 = ""
var set = Set<Character>()
for char in c {
set.insert(char)
}
for char in s {
if!set.contains(char) {
result.append(char)
}
}
return (result, result.reversed() == result)
}
```
if!set.contains(char) { // expected expression, var, or let in 'if' condition
return (result, result.reversed() == result) // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if c.contains(char) {
isPalindrome = false
} else {
result.append(char)
}
}
return (String(result.reversed()), 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) {
isPalindrome = false
} else {
result.append(char)
}
}
return (String(result.reversed()), isPalindrome)
}
```
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if c.contains(char) {
isPalindrome = false
} else {
result.append(char)
}
}
return (String(result.reversed()), 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) {
isPalindrome = false
} else {
result.append(char)
}
}
return (String(result.reversed()), isPalindrome)
}
```
// XCTAssertTrue failed
```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 = false
var isPalindrome2 = false
var isPalindrome3 = false
var isPalindrome4 = false
var isPalindrome5 = false
var isPalindrome6 = false
var isPalindrome7 = false
var isPalindrome8 = false
var isPalindrome9 = false
var isPalindrome10 = false
var isPalindrome11 = false
var isPalindrome12 = false
var isPalindrome13 = false
var isPalindrome14 = false
var isPalindrome15 = false
var isPalindrome16 = false
var isPalindrome17 = false
var isPalindrome18 = false
var isPalindrome19 = false
var isPalindrome20 = false
var isPalindrome21 = false
var isPalindrome22 = false
var isPalindrome23 = false
var isPalindrome24 = false
var isPalindrome25 = false
var isPalindrome26 = false
var isPalindrome27 = false
var isPalindrome28 = false
var isPalindrome29 = false
var isPalindrome30 = false
var isPalindrome31 = false
var isPalindrome32 = false
var isPalindrome33 = false
var isPalindrome34 = false
var isPalindrome35 = false
var isPalindrome36 = false
var isPalindrome37 = false
var isPalindrome38 = false
var isPalindrome39 = false
var isPalindrome40 = false
var isPalindrome41 = false
var isPalindrome42 = false
var isPalindrome43 = false
var isPalindrome44 = false
var isPalindrome45 = false
var isPalindrome46 = false
var isPalindrome47 = false
var isPalindrome48 = false
var isPalindrome49 = false
var isPalindrome50 = false
var isPalindrome51 = false
var isPalindrome52 = false
var isPalindrome53 = false
var isPalindrome54 = false
var isPalindrome55 = false
var isPalindrome56 = false
var isPalindrome57 = false
var isPalindrome58 = false
var isPalindrome59 = false
var isPalindrome60 = false
var isPalindrome61 = false
var isPalindrome62 = false
var isPalindrome63 = false
var isPalindrome64 = false
var isPalindrome65 = false
var isPalindrome66 = false
var isPalindrome67 = false
var isPalindrome68 = false
var isPalindrome69 = false
var isPalindrome70 = false
var isPalindrome71 = false
var isPalindrome72 = false
var isPalindrome73 = false
var isPalindrome74 = false
var isPalindrome75 = false
var isPalindrome76 = false
var isPalindrome77 = false
var isPalindrome78 = false
var isPalindrome79 = false
var isPalindrome80 = false
var isPalindrome81 = false
var isPalindrome82 = false
var isPalindrome83 = false
var isPalindrome84 = false
var isPalindrome85 = false
var isPalindrome86 = false
var isPalindrome87 = false
var isPalindrome88 = false
var isPalindrome89 = false
var isPalindrome90 = false
var isPalindrome91 = false
var isPalindrome92 = false
var isPalindrome93 = false
var isPalindrome94 = false
var isPalindrome95 = false
var isPalindrome96 = false
var isPalindrome97 = false
var isPalindrome98 = false
var isPalindrome99 = false
var isPalindrome100 = false
var isPalindrome101 = false
var isPalindrome102 = false
var isPalindrome103 = false
var isPalindrome104 = false
var isPalindrome105 = false
var isPalindrome106 = false
var isPalindrome107 = false
var isPalindrome108 = false
var isPalindrome109 = false
var isPalindrome110 = false
var isPalindrome111 = false
var isPalindrome112 = false
var isPalindrome113
XCTAssertTrue(reverseDelete(s: "abcde", c: "ae") == ("bcd", false)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "abcdef", c: "b") == ("acdef", false)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "dwik", c: "w") == ("dik", false)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "a", c: "a") == ("", true)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "abcdedcba", c: "") == ("abcdedcba", true)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "abcdedcba", c: "v") == ("abcdedcba", true)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "vabba", c: "v") == ("abba", true)) // cannot find 'reverseDelete' in scope
XCTAssertTrue(reverseDelete(s: "mamma", c: "mia") == ("", true)) // cannot find 'reverseDelete' in scope
func oddCount(lst: [String]) -> [String] {
return lst.enumerated().map { (index, string) -> String in
let count = string.filter { $0.isMultiple(of: 2) }.count
return "the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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.enumerated().map { (index, string) -> String in
let count = string.filter { $0.isMultiple(of: 2) }.count
return "the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput."
}
}
```
let count = string.filter { $0.isMultiple(of: 2) }.count // value of type 'String.Element' (aka 'Character') has no member 'isMultiple'
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, string) in lst.enumerated() {
let oddCount = string.filter { Int($0) % 2!= 0 }.count
result.append("the number of odd elements \(oddCount)n the str\(index)ng \(index) of the \(index)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 (index, string) in lst.enumerated() {
let oddCount = string.filter { Int($0) % 2!= 0 }.count
result.append("the number of odd elements \(oddCount)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
```
let oddCount = string.filter { Int($0) % 2!= 0 }.count // cannot force unwrap value of non-optional type 'Int'
let oddCount = string.filter { Int($0) % 2!= 0 }.count // expression is not assignable: binary operator returns immutable value
let oddCount = string.filter { Int($0) % 2!= 0 }.count // no exact matches in call to initializer
let oddCount = string.filter { Int($0) % 2!= 0 }.count // cannot convert value of type '()' to closure result type 'Bool'
let oddCount = string.filter { Int($0) % 2!= 0 }.count // '=' must have consistent whitespace on both sides
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, value) in lst.enumerated() {
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, value) in lst.enumerated() {
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
oddCount(lst: ["1234567"])
oddCount(lst: ["3", "11111111"])
```
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count // cannot convert value of type '()' to closure result type 'Bool'
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count // cannot force unwrap value of non-optional type 'Int'
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count // expression is not assignable: binary operator returns immutable value
let count = value.filter { $0.isNumber }.filter { Int($0)! % 2!= 0 }.count // '=' must have consistent whitespace on both sides
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, string) in lst.enumerated() {
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2!= 0 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, string) in lst.enumerated() {
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2!= 0 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
```
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2!= 0 }.count // expression is not assignable: binary operator returns immutable value
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2!= 0 }.count // cannot force unwrap value of non-optional type 'Int'
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2!= 0 }.count // cannot convert value of type '()' to closure result type 'Bool'
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2!= 0 }.count // '=' must have consistent whitespace on both sides
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, value) in lst.enumerated() {
var count = 0
for char in value {
if Int(String(char))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, value) in lst.enumerated() {
var count = 0
for char in value {
if Int(String(char))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
oddCount(lst: ["1234567"])
oddCount(lst: ["3", "11111111"])
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, string) in lst.enumerated() {
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2 == 1 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, string) in lst.enumerated() {
let count = string.filter { $0.isNumber }.filter { Int($0.description)! % 2 == 1 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
oddCount(lst: ["1234567"])
oddCount(lst: ["3", "11111111"])
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2!= 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2!= 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
```
if Int(String(char))! % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if Int(String(char))! % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if Int(String(char))! % 2!= 0 { // '=' must have consistent whitespace on both sides
if Int(String(char))! % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for (index, str) in lst.enumerated() {
let count = str.filter { $0.isNumber }.filter { Int($0.description)! % 2 == 1 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)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 (index, str) in lst.enumerated() {
let count = str.filter { $0.isNumber }.filter { Int($0.description)! % 2 == 1 }.count
result.append("the number of odd elements \(count)n the str\(index)ng \(index) of the \(index)nput.")
}
return result
}
oddCount(lst: ["1234567"])
oddCount(lst: ["3", "11111111"])
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var min = Int.max
var sum = 0
for num in nums {
sum += num
if sum < min {
min = sum
}
if sum > 0 {
sum = 0
}
}
return min
}
```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 min = Int.max
var sum = 0
for num in nums {
sum += num
if sum < min {
min = sum
}
if sum > 0 {
sum = 0
}
}
return min
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
if sum < minSum {
minSum = sum
}
if sum > 0 {
sum = 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 sum = 0
for num in nums {
sum += num
if sum < minSum {
minSum = sum
}
if sum > 0 {
sum = 0
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 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 sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var min = Int.max
var sum = 0
for num in nums {
sum += num
if sum < min {
min = sum
}
if sum > 0 {
sum = 0
}
}
return min
}
```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 min = Int.max
var sum = 0
for num in nums {
sum += num
if sum < min {
min = sum
}
if sum > 0 {
sum = 0
}
}
return min
}
```
func maxFill(grid: [[Int]], capacity: Int) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var maxFill = 0
var grid = grid
var capacity = capacity
while!grid.isEmpty {
var row = grid.removeFirst()
var count = 0
while!row.isEmpty {
if row.removeFirst() == 1 {
count += 1
}
}
if count > 0 {
maxFill += 1
capacity -= count
}
}
return maxFill
}
```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 maxFill = 0
var grid = grid
var capacity = capacity
while!grid.isEmpty {
var row = grid.removeFirst()
var count = 0
while!row.isEmpty {
if row.removeFirst() == 1 {
count += 1
}
}
if count > 0 {
maxFill += 1
capacity -= count
}
}
return maxFill
}
```
while!grid.isEmpty { // expected expression, var, or let in 'while' condition
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var grid = grid
var capacity = capacity
while!grid.allSatisfy({ $0.allSatisfy({ $0 == 0 }) }) {
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i == 0 {
grid[i][j] = 0
count += 1
} else {
grid[i][j] = 0
grid[i - 1][j] = 1
count += 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
var grid = grid
var capacity = capacity
while!grid.allSatisfy({ $0.allSatisfy({ $0 == 0 }) }) {
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i == 0 {
grid[i][j] = 0
count += 1
} else {
grid[i][j] = 0
grid[i - 1][j] = 1
count += 1
}
}
}
}
}
return count
}
```
while!grid.allSatisfy({ $0.allSatisfy({ $0 == 0 }) }) { // expected expression, var, or let in 'while' condition
func maxFill(grid: [[Int]], capacity: Int) -> Int {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var grid = grid
var capacity = capacity
while!grid.isEmpty {
var row = grid.removeFirst()
var index = 0
while index < row.count {
if row[index] == 1 {
row[index] = 0
count += 1
capacity -= 1
if capacity == 0 {
break
}
}
index += 1
}
if capacity == 0 {
break
}
}
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
var grid = grid
var capacity = capacity
while!grid.isEmpty {
var row = grid.removeFirst()
var index = 0
while index < row.count {
if row[index] == 1 {
row[index] = 0
count += 1
capacity -= 1
if capacity == 0 {
break
}
}
index += 1
}
if capacity == 0 {
break
}
}
return count
}
```
while!grid.isEmpty { // expected expression, var, or let in 'while' condition
func maxFill(grid: [[Int]], capacity: Int) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var grid = grid
while!grid.isEmpty {
var newGrid = [[Int]]()
for row in grid {
var newRow = [Int]()
for i in 0..<row.count {
if row[i] == 1 {
newRow.append(0)
} else {
newRow.append(1)
}
}
newGrid.append(newRow)
}
grid = newGrid
count += 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
var grid = grid
while!grid.isEmpty {
var newGrid = [[Int]]()
for row in grid {
var newRow = [Int]()
for i in 0..<row.count {
if row[i] == 1 {
newRow.append(0)
} else {
newRow.append(1)
}
}
newGrid.append(newRow)
}
grid = newGrid
count += 1
}
return count
}
```
while!grid.isEmpty { // expected expression, var, or let in 'while' condition
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var grid = grid
var capacity = capacity
while grid.count > 0 {
var row = grid.removeFirst()
while row.count > 0 {
let cell = row.removeFirst()
if cell == 1 {
count += 1
capacity -= 1
}
if capacity == 0 {
break
}
}
if capacity == 0 {
break
}
}
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
var grid = grid
var capacity = capacity
while grid.count > 0 {
var row = grid.removeFirst()
while row.count > 0 {
let cell = row.removeFirst()
if cell == 1 {
count += 1
capacity -= 1
}
if capacity == 0 {
break
}
}
if capacity == 0 {
break
}
}
return count
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String($0, radix: 2).components(separatedBy: "1").count
let b = String($1, radix: 2).components(separatedBy: "1").count
return a == b? $0 < $1 : a < b
}
}
```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 {
let a = String($0, radix: 2).components(separatedBy: "1").count
let b = String($1, radix: 2).components(separatedBy: "1").count
return a == b? $0 < $1 : a < b
}
}
```
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // expected expression
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // cannot use optional chaining on non-optional value of type 'Int'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String($0, radix: 2).components(separatedBy: "1").count
let b = String($1, radix: 2).components(separatedBy: "1").count
return a == b? $0 < $1 : a < b
}
}
```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 {
let a = String($0, radix: 2).components(separatedBy: "1").count
let b = String($1, radix: 2).components(separatedBy: "1").count
return a == b? $0 < $1 : a < b
}
}
```
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // expected expression
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // cannot use optional chaining on non-optional value of type 'Int'
func sortArray(arr: [Int]) -> [Int] {
let sorted = arr.sorted {
let (a, b) = ($0, $1)
let aCount = String(a, radix: 2).filter { $0 == "1" }.count
let bCount = String(b, radix: 2).filter { $0 == "1" }.count
if aCount == bCount {
return a < b
} else {
return aCount < bCount
}
}
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 {
let (a, b) = ($0, $1)
let aCount = String(a, radix: 2).filter { $0 == "1" }.count
let bCount = String(b, radix: 2).filter { $0 == "1" }.count
if aCount == bCount {
return a < b
} else {
return aCount < bCount
}
}
return sorted
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aCount = String(a, radix: 2).components(separatedBy: "1").count
let bCount = String(b, radix: 2).components(separatedBy: "1").count
if aCount == bCount {
return a < b
} else {
return aCount < bCount
}
}
}
```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 aCount = String(a, radix: 2).components(separatedBy: "1").count
let bCount = String(b, radix: 2).components(separatedBy: "1").count
if aCount == bCount {
return a < b
} else {
return aCount < bCount
}
}
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aCount = String(a, radix: 2).filter { $0 == "1" }.count
let bCount = String(b, radix: 2).filter { $0 == "1" }.count
if aCount == bCount {
return a < b
} else {
return aCount < bCount
}
}
}
```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 aCount = String(a, radix: 2).filter { $0 == "1" }.count
let bCount = String(b, radix: 2).filter { $0 == "1" }.count
if aCount == bCount {
return a < b
} else {
return aCount < bCount
}
}
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String($0, radix: 2).components(separatedBy: "1").count
let b = String($1, radix: 2).components(separatedBy: "1").count
if a == b {
return $0 < $1
} else {
return a < b
}
}
}
```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 {
let a = String($0, radix: 2).components(separatedBy: "1").count
let b = String($1, radix: 2).components(separatedBy: "1").count
if a == b {
return $0 < $1
} else {
return a < b
}
}
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let (a, b) = ($0, $1)
let (aOnes, bOnes) = (a.numberOfOnes, b.numberOfOnes)
if aOnes == bOnes {
return a < b
} else {
return aOnes < bOnes
}
}
}
extension Int {
var numberOfOnes: Int {
var count = 0
var n = self
while n > 0 {
if n % 2 == 1 {
count += 1
}
n /= 2
}
return 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 {
let (a, b) = ($0, $1)
let (aOnes, bOnes) = (a.numberOfOnes, b.numberOfOnes)
if aOnes == bOnes {
return a < b
} else {
return aOnes < bOnes
}
}
}
extension Int {
var numberOfOnes: Int {
var count = 0
var n = self
while n > 0 {
if n % 2 == 1 {
count += 1
}
n /= 2
}
return count
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let (a, b) = ($0, $1)
let (aOnes, bOnes) = (a.numberOfOnes, b.numberOfOnes)
if aOnes == bOnes {
return a < b
}
return aOnes < bOnes
}
}
extension Int {
var numberOfOnes: Int {
var count = 0
var n = self
while n > 0 {
count += n & 1
n >>= 1
}
return 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 {
let (a, b) = ($0, $1)
let (aOnes, bOnes) = (a.numberOfOnes, b.numberOfOnes)
if aOnes == bOnes {
return a < b
}
return aOnes < bOnes
}
}
extension Int {
var numberOfOnes: Int {
var count = 0
var n = self
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
let sorted = arr.sorted { (a, b) -> Bool in
let aOnes = String(a, radix: 2).filter { $0 == "1" }.count
let bOnes = String(b, radix: 2).filter { $0 == "1" }.count
if aOnes == bOnes {
return a < b
} else {
return aOnes < bOnes
}
}
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 { (a, b) -> Bool in
let aOnes = String(a, radix: 2).filter { $0 == "1" }.count
let bOnes = String(b, radix: 2).filter { $0 == "1" }.count
if aOnes == bOnes {
return a < b
} else {
return aOnes < bOnes
}
}
return sorted
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aOnes = a.numberOfOnes()
let bOnes = b.numberOfOnes()
if aOnes == bOnes {
return a < b
}
return aOnes < bOnes
}
}
extension Int {
func numberOfOnes() -> Int {
var count = 0
var n = self
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return 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 { (a, b) -> Bool in
let aOnes = a.numberOfOnes()
let bOnes = b.numberOfOnes()
if aOnes == bOnes {
return a < b
}
return aOnes < bOnes
}
}
extension Int {
func numberOfOnes() -> Int {
var count = 0
var n = self
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(String(char)) {
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 vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(String(char)) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(String(char)) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(char) {
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 vowels = "aeiou"
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(char) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(char) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = ["a", "e", "i", "o", "u"]
var result = [String]()
let words = s.components(separatedBy: " ")
for word in words {
var consonants = 0
for letter in word {
if!vowels.contains(String(letter)) {
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 vowels = ["a", "e", "i", "o", "u"]
var result = [String]()
let words = s.components(separatedBy: " ")
for word in words {
var consonants = 0
for letter in word {
if!vowels.contains(String(letter)) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(String(letter)) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
var result = [String]()
let words = s.components(separatedBy: " ")
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(char) {
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 vowels = "aeiou"
var result = [String]()
let words = s.components(separatedBy: " ")
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(char) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(char) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if!vowels.contains(char) {
count += 1
}
}
if count == 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 vowels = "aeiou"
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if!vowels.contains(char) {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(char) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for letter in word {
if!vowels.contains(String(letter)) {
count += 1
}
}
if count == 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 vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for letter in word {
if!vowels.contains(String(letter)) {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(String(letter)) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(String(char)) {
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 vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(String(char)) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(String(char)) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(String(char)) {
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 vowels = ["a", "e", "i", "o", "u"]
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(String(char)) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(String(char)) { // expected expression, var, or let in 'if' condition
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
let words = s.split(separator: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if vowels.contains(char) {
break
} else {
consonants += 1
}
}
if consonants == n {
result.append(String(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 vowels = "aeiou"
let words = s.split(separator: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if vowels.contains(char) {
break
} else {
consonants += 1
}
}
if consonants == n {
result.append(String(word))
}
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(char) {
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 vowels = "aeiou"
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if!vowels.contains(char) {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if!vowels.contains(char) { // expected expression, var, or let in 'if' condition
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
var index = word.count - 1
var isVowel = false
while index >= 0 {
let char = word[index]
if vowels.contains(String(char)) {
isVowel = true
}
if isVowel &&!vowels.contains(String(char)) {
result = String(char)
break
}
index -= 1
}
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 = ""
var index = word.count - 1
var isVowel = false
while index >= 0 {
let char = word[index]
if vowels.contains(String(char)) {
isVowel = true
}
if isVowel &&!vowels.contains(String(char)) {
result = String(char)
break
}
index -= 1
}
return result
}
```
var vowels = ["a", "e", "i", "o", "u"] // variable 'vowels' was never mutated; consider changing to 'let' constant
let char = word[index] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if isVowel &&!vowels.contains(String(char)) { // expected '{' after 'if' condition
func getClosestVowel(word: String) -> String {
var vowels = "aeiou"
var closestVowel = ""
var closestVowelIndex = 0
var closestVowelDistance = 0
var lastConsonantIndex = 0
var lastConsonant = ""
var lastConsonantDistance = 0
var lastConsonantFound = false
var vowelFound = false
for (index, letter) in word.enumerated() {
if vowels.contains(letter) {
if!vowelFound {
vowelFound = true
closestVowel = String(letter)
closestVowelIndex = index
closestVowelDistance = index
} else {
if index - lastConsonantIndex < closestVowelDistance {
closestVowel = String(letter)
closestVowelIndex = index
closestVowelDistance = index - lastConsonantIndex
}
}
} else {
if!lastConsonantFound {
lastConsonant = String(letter)
lastConsonantIndex = index
lastConsonantDistance = index
lastConsonantFound = true
} else {
if index - lastConsonantIndex < lastConsonantDistance {
lastConsonant = String(letter)
lastConsonantIndex = index
lastConsonantDistance = index - lastConsonantIndex
}
}
}
}
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 {
var vowels = "aeiou"
var closestVowel = ""
var closestVowelIndex = 0
var closestVowelDistance = 0
var lastConsonantIndex = 0
var lastConsonant = ""
var lastConsonantDistance = 0
var lastConsonantFound = false
var vowelFound = false
for (index, letter) in word.enumerated() {
if vowels.contains(letter) {
if!vowelFound {
vowelFound = true
closestVowel = String(letter)
closestVowelIndex = index
closestVowelDistance = index
} else {
if index - lastConsonantIndex < closestVowelDistance {
closestVowel = String(letter)
closestVowelIndex = index
closestVowelDistance = index - lastConsonantIndex
}
}
} else {
if!lastConsonantFound {
lastConsonant = String(letter)
lastConsonantIndex = index
lastConsonantDistance = index
lastConsonantFound = true
} else {
if index - lastConsonantIndex < lastConsonantDistance {
lastConsonant = String(letter)
lastConsonantIndex = index
lastConsonantDistance = index - lastConsonantIndex
}
}
}
}
return closestVowel
}
```
if!vowelFound { // expected expression, var, or let in 'if' condition
if!lastConsonantFound { // expected expression, var, or let in 'if' condition
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let wordArray = Array(word)
var closestVowel: String = ""
var closestVowelIndex = 0
var vowelIndex = 0
var consonantIndex = 0
var consonantCount = 0
var vowelCount = 0
var isVowel = false
var isConsonant = false
for letter in wordArray {
if vowels.contains(String(letter)) {
isVowel = true
vowelIndex = wordArray.index(of: letter)!
vowelCount += 1
}
if!vowels.contains(String(letter)) {
isConsonant = true
consonantIndex = wordArray.index(of: letter)!
consonantCount += 1
}
if isVowel && isConsonant {
if consonantIndex > vowelIndex {
if vowelCount > 1 {
if vowelIndex - consonantIndex < closestVowelIndex - consonantIndex {
closestVowel = String(letter)
closestVowelIndex = vowelIndex
}
}
}
}
isVowel = false
isConsonant = false
}
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 wordArray = Array(word)
var closestVowel: String = ""
var closestVowelIndex = 0
var vowelIndex = 0
var consonantIndex = 0
var consonantCount = 0
var vowelCount = 0
var isVowel = false
var isConsonant = false
for letter in wordArray {
if vowels.contains(String(letter)) {
isVowel = true
vowelIndex = wordArray.index(of: letter)!
vowelCount += 1
}
if!vowels.contains(String(letter)) {
isConsonant = true
consonantIndex = wordArray.index(of: letter)!
consonantCount += 1
}
if isVowel && isConsonant {
if consonantIndex > vowelIndex {
if vowelCount > 1 {
if vowelIndex - consonantIndex < closestVowelIndex - consonantIndex {
closestVowel = String(letter)
closestVowelIndex = vowelIndex
}
}
}
}
isVowel = false
isConsonant = false
}
return closestVowel
}
```
vowelIndex = wordArray.index(of: letter)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
if!vowels.contains(String(letter)) { // expected expression, var, or let in 'if' condition
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel: Character?
var closestVowelIndex = 0
for (index, char) in word.enumerated() {
if vowels.contains(char) {
if closestVowel == nil || index < closestVowelIndex {
closestVowel = char
closestVowelIndex = index
}
}
}
return String(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: Character?
var closestVowelIndex = 0
for (index, char) in word.enumerated() {
if vowels.contains(char) {
if closestVowel == nil || index < closestVowelIndex {
closestVowel = char
closestVowelIndex = index
}
}
}
return String(closestVowel?? "")
}
```
return String(closestVowel?? "") // value of optional type 'String?' must be unwrapped to a value of type 'String'
return String(closestVowel?? "") // cannot use optional chaining on non-optional value of type 'Character'
return String(closestVowel?? "") // initializer 'init(bytes:encoding:)' requires that 'Character?' conform to 'Sequence'
return String(closestVowel?? "") // missing argument labels 'bytes:encoding:' in call
return String(closestVowel?? "") // cannot convert value of type 'String' to expected argument type 'String.Encoding'
return String(closestVowel?? "") // expected ',' separator
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var closestVowel = ""
var closestVowelIndex = 0
var closestVowelDistance = 0
var distance = 0
var vowelFound = false
for i in 0..<word.count {
for j in 0..<vowels.count {
if word[i] == vowels[j] {
vowelFound = true
distance = word.count - i
if distance < closestVowelDistance || closestVowelDistance == 0 {
closestVowelDistance = distance
closestVowelIndex = i
closestVowel = vowels[j]
}
}
}
}
if vowelFound {
return String(closestVowel)
} else {
return ""
}
}
```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 closestVowel = ""
var closestVowelIndex = 0
var closestVowelDistance = 0
var distance = 0
var vowelFound = false
for i in 0..<word.count {
for j in 0..<vowels.count {
if word[i] == vowels[j] {
vowelFound = true
distance = word.count - i
if distance < closestVowelDistance || closestVowelDistance == 0 {
closestVowelDistance = distance
closestVowelIndex = i
closestVowel = vowels[j]
}
}
}
}
if vowelFound {
return String(closestVowel)
} else {
return ""
}
}
```
if word[i] == vowels[j] { // no exact matches in call to subscript
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
var index = word.count - 1
var vowelIndex = -1
var consonantIndex = -1
while index >= 0 {
if vowels.contains(word[index]) {
vowelIndex = index
break
}
index -= 1
}
index = word.count - 1
while index >= 0 {
if!vowels.contains(word[index]) {
consonantIndex = index
break
}
index -= 1
}
if vowelIndex == -1 || consonantIndex == -1 {
return ""
}
if consonantIndex - vowelIndex == 1 {
return ""
}
index = vowelIndex - 1
while index >= 0 {
if!vowels.contains(word[index]) {
result = word[index]
break
}
index -= 1
}
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 = ""
var index = word.count - 1
var vowelIndex = -1
var consonantIndex = -1
while index >= 0 {
if vowels.contains(word[index]) {
vowelIndex = index
break
}
index -= 1
}
index = word.count - 1
while index >= 0 {
if!vowels.contains(word[index]) {
consonantIndex = index
break
}
index -= 1
}
if vowelIndex == -1 || consonantIndex == -1 {
return ""
}
if consonantIndex - vowelIndex == 1 {
return ""
}
index = vowelIndex - 1
while index >= 0 {
if!vowels.contains(word[index]) {
result = word[index]
break
}
index -= 1
}
return result
}
```
if vowels.contains(word[index]) { // cannot convert value of type 'Character' to expected argument type 'String'
if!vowels.contains(word[index]) { // expected expression, var, or let in 'if' condition
if!vowels.contains(word[index]) { // expected expression, var, or let in 'if' condition
```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 wordArray = Array(word)
var result = ""
var index = 0
var vowelIndex = 0
var vowelIndex2 = 0
var vowelIndex3 = 0
var vowelIndex4 = 0
var vowelIndex5 = 0
var vowelIndex6 = 0
var vowelIndex7 = 0
var vowelIndex8 = 0
var vowelIndex9 = 0
var vowelIndex10 = 0
var vowelIndex11 = 0
var vowelIndex12 = 0
var vowelIndex13 = 0
var vowelIndex14 = 0
var vowelIndex15 = 0
var vowelIndex16 = 0
var vowelIndex17 = 0
var vowelIndex18 = 0
var vowelIndex19 = 0
var vowelIndex20 = 0
var vowelIndex21 = 0
var vowelIndex22 = 0
var vowelIndex23 = 0
var vowelIndex24 = 0
var vowelIndex25 = 0
var vowelIndex26 = 0
var vowelIndex27 = 0
var vowelIndex28 = 0
var vowelIndex29 = 0
var vowelIndex30 = 0
var vowelIndex31 = 0
var vowelIndex32 = 0
var vowelIndex33 = 0
var vowelIndex34 = 0
var vowelIndex35 = 0
var vowelIndex36 = 0
var vowelIndex37 = 0
var vowelIndex38 = 0
var vowelIndex39 = 0
var vowelIndex40 = 0
var vowelIndex41 = 0
var vowelIndex42 = 0
var vowelIndex43 = 0
var vowelIndex44 = 0
var vowelIndex45 = 0
var vowelIndex46 = 0
var vowelIndex47 = 0
var vowelIndex48 = 0
var vowelIndex49 = 0
var vowelIndex50 = 0
var vowelIndex51 = 0
var vowelIndex52 = 0
var vowelIndex53 = 0
var vowelIndex54 = 0
var vowelIndex55 = 0
var vowelIndex56 = 0
var vowelIndex57 = 0
var vowelIndex58 = 0
var vowelIndex59 = 0
var vowelIndex60 = 0
var vowelIndex61 = 0
var vowelIndex62 = 0
var vowelIndex63 = 0
var vowelIndex64 = 0
var vowelIndex65 = 0
var vowelIndex66 = 0
var vowelIndex67 = 0
var vowelIndex68 = 0
var vowelIndex69 = 0
var vowelIndex70 = 0
var vowelIndex71 = 0
var vowelIndex72 = 0
var vowelIndex73 = 0
var vowelIndex74 = 0
var vowelIndex75 = 0
var vowelIndex76 = 0
var vowelIndex77 = 0
var vowelIndex78 = 0
var vowelIndex79 = 0
var vowelIndex80 = 0
var vowelIndex81 = 0
var vowelIndex82 = 0
var vowelIndex83 = 0
var vowelIndex84 = 0
var vowelIndex85 = 0
var vowelIndex86 = 0
var vowelIndex87 = 0
var vowelIndex88 = 0
var vowelIndex89 = 0
var vowelIndex90 = 0
var vowelIndex91 = 0
var vowelIndex92 = 0
var vowelIndex93 = 0
var vowelIndex94 = 0
var vowelIndex95 = 0
var vowelIndex96 = 0
var vowelIndex97 = 0
var vowelIndex98 = 0
var vowelIndex99 = 0
var v
XCTAssertTrue(getClosestVowel(word: "yogurt") == "u") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "full") == "u") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "easy") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "eAsy") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "ali") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "bad") == "a") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "most") == "o") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "ab") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "ba") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "quick") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "anime") == "i") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "Asia") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "Above") == "o") // cannot find 'getClosestVowel' in scope
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
var index = word.index(word.endIndex, offsetBy: -1)
while index >= word.startIndex {
let char = word[index]
if vowels.contains(String(char)) {
result = String(char)
break
}
index = word.index(before: index)
}
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"]
var result = ""
var index = word.index(word.endIndex, offsetBy: -1)
while index >= word.startIndex {
let char = word[index]
if vowels.contains(String(char)) {
result = String(char)
break
}
index = word.index(before: index)
}
return result
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let wordArr = Array(word)
var closestVowel = ""
var closestVowelIndex = 0
var closestVowelDistance = 0
var vowelIndex = 0
var vowelDistance = 0
var consonantIndex = 0
var consonantDistance = 0
for i in 0..<wordArr.count {
if vowels.contains(String(wordArr[i])) {
vowelIndex = i
vowelDistance = wordArr.count - vowelIndex
if closestVowelDistance == 0 {
closestVowelDistance = vowelDistance
closestVowelIndex = vowelIndex
closestVowel = String(wordArr[i])
} else if closestVowelDistance > vowelDistance {
closestVowelDistance = vowelDistance
closestVowelIndex = vowelIndex
closestVowel = String(wordArr[i])
}
} else {
consonantIndex = i
consonantDistance = wordArr.count - consonantIndex
if closestVowelDistance == 0 {
closestVowelDistance = consonantDistance
closestVowelIndex = consonantIndex
closestVowel = ""
} else if closestVowelDistance > consonantDistance {
closestVowelDistance = consonantDistance
closestVowelIndex = consonantIndex
closestVowel = ""
}
}
}
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 wordArr = Array(word)
var closestVowel = ""
var closestVowelIndex = 0
var closestVowelDistance = 0
var vowelIndex = 0
var vowelDistance = 0
var consonantIndex = 0
var consonantDistance = 0
for i in 0..<wordArr.count {
if vowels.contains(String(wordArr[i])) {
vowelIndex = i
vowelDistance = wordArr.count - vowelIndex
if closestVowelDistance == 0 {
closestVowelDistance = vowelDistance
closestVowelIndex = vowelIndex
closestVowel = String(wordArr[i])
} else if closestVowelDistance > vowelDistance {
closestVowelDistance = vowelDistance
closestVowelIndex = vowelIndex
closestVowel = String(wordArr[i])
}
} else {
consonantIndex = i
consonantDistance = wordArr.count - consonantIndex
if closestVowelDistance == 0 {
closestVowelDistance = consonantDistance
closestVowelIndex = consonantIndex
closestVowel = ""
} else if closestVowelDistance > consonantDistance {
closestVowelDistance = consonantDistance
closestVowelIndex = consonantIndex
closestVowel = ""
}
}
}
return closestVowel
}
getClosestVowel(word: "yogurt")
getClosestVowel(word: "FULL")
getClosestVowel(word: "quick")
getClosestVowel(word: "ab")
```
var closestVowelIndex = 0 // variable 'closestVowelIndex' was written to, but never read
// XCTAssertTrue failed
```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 closestVowel: String = ""
var closestVowelIndex: Int = 0
var vowelIndex: Int = 0
var consonantIndex: Int = 0
var consonantCount: Int = 0
var vowelCount: Int = 0
var vowelFound: Bool = false
var consonantFound: Bool = false
var vowelFoundInConsonant: Bool = false
var consonantFoundInVowel: Bool = false
var vowelFoundInConsonantCount: Int = 0
var consonantFoundInVowelCount: Int = 0
var vowelFoundInConsonantIndex: Int = 0
var consonantFoundInVowelIndex: Int = 0
var vowelFoundInConsonantIndexCount: Int = 0
var consonantFoundInVowelIndexCount: Int = 0
var vowelFoundInConsonantIndexCount2: Int = 0
var consonantFoundInVowelIndexCount2: Int = 0
var vowelFoundInConsonantIndexCount3: Int = 0
var consonantFoundInVowelIndexCount3: Int = 0
var vowelFoundInConsonantIndexCount4: Int = 0
var consonantFoundInVowelIndexCount4: Int = 0
var vowelFoundInConsonantIndexCount5: Int = 0
var consonantFoundInVowelIndexCount5: Int = 0
var vowelFoundInConsonantIndexCount6: Int = 0
var consonantFoundInVowelIndexCount6: Int = 0
var vowelFoundInConsonantIndexCount7: Int = 0
var consonantFoundInVowelIndexCount7: Int = 0
var vowelFoundInConsonantIndexCount8: Int = 0
var consonantFoundInVowelIndexCount8: Int = 0
var vowelFoundInConsonantIndexCount9: Int = 0
var consonantFoundInVowelIndexCount9: Int = 0
var vowelFoundInConsonantIndexCount10: Int = 0
var consonantFoundInVowelIndexCount10: Int = 0
var vowelFoundInConsonantIndexCount11: Int = 0
var consonantFoundInVowelIndexCount11: Int = 0
var vowelFoundInConsonantIndexCount12: Int = 0
var consonantFoundInVowelIndexCount12: Int = 0
var vowelFoundInConsonantIndexCount13: Int = 0
var consonantFoundInVowelIndexCount13: Int = 0
var vowelFoundInConsonantIndexCount14: Int = 0
var consonantFoundInVowelIndexCount14: Int = 0
var vowelFoundInConsonantIndexCount15: Int = 0
var consonantFoundInVowelIndexCount15: Int = 0
var vowelFoundInConsonantIndexCount16: Int = 0
var consonantFoundInVowelIndexCount16: Int = 0
var vowelFoundInConsonantIndexCount17: Int = 0
var consonantFoundInVowelIndexCount17: Int = 0
var vowelFoundInConsonantIndexCount18: Int = 0
var consonantFoundInVowelIndexCount18: Int = 0
var vowelFoundInConsonantIndexCount19: Int = 0
var consonantFoundInVowelIndexCount19: Int = 0
var vowelFoundInConsonantIndexCount20: Int = 0
var consonantFoundInVowelIndexCount20: Int = 0
var vowelFoundInConsonantIndexCount21: Int = 0
var consonantFoundInVowelIndexCount21: Int = 0
var vowelFoundInConsonantIndexCount22: Int = 0
var consonantFoundInVowelIndexCount22: Int = 0
var vowelFoundInConsonantIndexCount23: Int = 0
var consonantFoundInVowelIndexCount23: Int = 0
var vowelFoundInConsonantIndexCount24: Int = 0
var consonantFoundInVowelIndex
XCTAssertTrue(getClosestVowel(word: "yogurt") == "u") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "full") == "u") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "easy") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "eAsy") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "ali") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "bad") == "a") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "most") == "o") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "ab") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "ba") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "quick") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "anime") == "i") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "Asia") == "") // cannot find 'getClosestVowel' in scope
XCTAssertTrue(getClosestVowel(word: "Above") == "o") // cannot find 'getClosestVowel' in scope
func matchParens(lst: [String]) -> String {
var stack = [String]()
for char in lst {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
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(char)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
if str == "(" {
stack.append(str)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
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 str in lst {
if str == "(" {
stack.append(str)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [Character]()
for char in lst[0] {
stack.append(char)
}
for char in lst[1] {
if stack.isEmpty {
return "No"
}
if char == ")" {
if stack.last == "(" {
stack.removeLast()
} else {
return "No"
}
} else {
stack.append(char)
}
}
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 = [Character]()
for char in lst[0] {
stack.append(char)
}
for char in lst[1] {
if stack.isEmpty {
return "No"
}
if char == ")" {
if stack.last == "(" {
stack.removeLast()
} else {
return "No"
}
} else {
stack.append(char)
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of 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.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
if str == "(" {
stack.append(str)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
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 str in lst {
if str == "(" {
stack.append(str)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of 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.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for item in lst {
if item == "(" {
stack.append(item)
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
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 item in lst {
if item == "(" {
stack.append(item)
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func matchParens(lst: [String]) -> String {
var stack = [Character]()
for char in lst[0] {
stack.append(char)
}
for char in lst[1] {
if stack.isEmpty {
return "No"
}
if char == ")" {
if stack.last == "(" {
stack.removeLast()
} else {
return "No"
}
} else {
stack.append(char)
}
}
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 = [Character]()
for char in lst[0] {
stack.append(char)
}
for char in lst[1] {
if stack.isEmpty {
return "No"
}
if char == ")" {
if stack.last == "(" {
stack.removeLast()
} else {
return "No"
}
} else {
stack.append(char)
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of 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"
} else {
stack.removeLast()
}
}
}
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"
} else {
stack.removeLast()
}
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func matchParens(lst: [String]) -> String {
var stack = [Character]()
for char in lst[0] {
stack.append(char)
}
for char in lst[1] {
if stack.isEmpty {
return "No"
}
if stack.last == "(" && char == ")" {
stack.removeLast()
} else {
return "No"
}
}
if stack.isEmpty {
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 {
var stack = [Character]()
for char in lst[0] {
stack.append(char)
}
for char in lst[1] {
if stack.isEmpty {
return "No"
}
if stack.last == "(" && char == ")" {
stack.removeLast()
} else {
return "No"
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap<Int>(sort: >)
for num in arr {
heap.push(num)
}
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<Int>(sort: >)
for num in arr {
heap.push(num)
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap<Int>(sort: >) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap(sort: { $0 > $1 })
for num in arr {
heap.push(num)
}
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(sort: { $0 > $1 })
for num in arr {
heap.push(num)
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap(sort: { $0 > $1 }) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap(sort: { $0 > $1 })
for num in arr {
heap.push(num)
}
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(sort: { $0 > $1 })
for num in arr {
heap.push(num)
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap(sort: { $0 > $1 }) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap(sort: >)
for i in arr {
heap.push(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(sort: >)
for i in arr {
heap.push(i)
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap(sort: >) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var queue = PriorityQueue<Int>()
for i in arr {
queue.enqueue(i)
}
for _ in 0..<k {
result.append(queue.dequeue()!)
}
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 queue = PriorityQueue<Int>()
for i in arr {
queue.enqueue(i)
}
for _ in 0..<k {
result.append(queue.dequeue()!)
}
return result
}
```
var queue = PriorityQueue<Int>() // cannot find 'PriorityQueue' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap<Int>(sort: >)
for i in arr {
heap.push(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<Int>(sort: >)
for i in arr {
heap.push(i)
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap<Int>(sort: >) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
guard arr.count > 0 else { return [] }
guard k > 0 else { return [] }
guard k <= arr.count else { return arr.sorted() }
var result = [Int]()
var heap = Heap(sort: >)
for num in arr {
heap.push(num)
}
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] {
guard arr.count > 0 else { return [] }
guard k > 0 else { return [] }
guard k <= arr.count else { return arr.sorted() }
var result = [Int]()
var heap = Heap(sort: >)
for num in arr {
heap.push(num)
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap(sort: >) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
guard arr.count > 0 else { return [] }
guard k > 0 else { return [] }
guard k <= arr.count else { return arr }
var result = [Int]()
var heap = Heap(sort: { $0 > $1 })
for i in 0..<arr.count {
heap.push(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] {
guard arr.count > 0 else { return [] }
guard k > 0 else { return [] }
guard k <= arr.count else { return arr }
var result = [Int]()
var heap = Heap(sort: { $0 > $1 })
for i in 0..<arr.count {
heap.push(arr[i])
}
for _ in 0..<k {
result.append(heap.pop()!)
}
return result
}
```
var heap = Heap(sort: { $0 > $1 }) // cannot find 'Heap' in scope
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```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 {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```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 {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```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 {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```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 {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```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 {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
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 (index, value) in lst.enumerated() {
if index % 2 == 0 {
sum += value
}
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
sum += arr[i]
}
return sum
}
```
// XCTAssertTrue failed
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 {
sum += arr[i]
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
sum += arr[i]
}
return sum
}
```
// XCTAssertTrue failed
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 {
sum += arr[i]
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
let num = arr[i]
if num < 100 {
sum += num
}
}
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 {
sum += arr[i]
}
return sum
}
```
// XCTAssertTrue failed
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 {
sum += arr[i]
}
return sum
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if result.contains(num) {
break
}
result.append(num)
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
result.append(num)
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
result.append(num)
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
return result.sorted()
}
```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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
return result.sorted()
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
return result.sorted()
}
```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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
return result.sorted()
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2 == 1 {
result.append(num)
}
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2 == 1 {
result.append(num)
}
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2 == 1 {
result.append(num)
}
}
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 num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = num * 3 + 1
}
if num % 2 == 1 {
result.append(num)
}
}
return result
}
```
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
result.append(num)
}
return result.filter { $0 % 2 == 1 }.sorted()
}
```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 num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
result.append(num)
}
return result.filter { $0 % 2 == 1 }.sorted()
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```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 dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```
return date!= nil // cannot assign through '!': 'date' is a 'let' constant
return date!= nil // use of '=' in a boolean context, did you mean '=='?
return date!= nil // 'nil' cannot be assigned to type 'Date'
return date!= nil // '=' must have consistent whitespace on both sides
func validDate(date: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func validDate(date: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func validDate(date: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func validDate(date: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func validDate(date: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func validDate(date: String) -> Bool {
return false
}
```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 {
return false
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: date) {
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
if year > 1900 && year < 2100 && month > 0 && month < 13 && day > 0 && day < 32 {
switch month {
case 1, 3, 5, 7, 8, 10, 12:
if day > 0 && day < 32 {
return true
}
case 4, 6, 9, 11:
if day > 0 && day < 31 {
return true
}
case 2:
if year % 4 == 0 {
if day > 0 && day < 30 {
return true
}
} else {
if day > 0 && day < 29 {
return true
}
}
default:
return false
}
}
}
return false
}
```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 dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: date) {
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
if year > 1900 && year < 2100 && month > 0 && month < 13 && day > 0 && day < 32 {
switch month {
case 1, 3, 5, 7, 8, 10, 12:
if day > 0 && day < 32 {
return true
}
case 4, 6, 9, 11:
if day > 0 && day < 31 {
return true
}
case 2:
if year % 4 == 0 {
if day > 0 && day < 30 {
return true
}
} else {
if day > 0 && day < 29 {
return true
}
}
default:
return false
}
}
}
return false
}
```
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: date) {
let calendar = Calendar.current
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
if month < 1 || month > 12 {
return false
}
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if year % 4 == 0 {
if day < 1 || day > 29 {
return false
}
} else {
if day < 1 || day > 28 {
return false
}
}
}
return true
}
return false
}
```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 dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: date) {
let calendar = Calendar.current
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
if month < 1 || month > 12 {
return false
}
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if year % 4 == 0 {
if day < 1 || day > 29 {
return false
}
} else {
if day < 1 || day > 28 {
return false
}
}
}
return true
}
return false
}
```
extension Int: Error {
}
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> {
return.failure(0)
}
```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> {
return.failure(0)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
// TODO: Implement
}
```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> {
// TODO: Implement
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
return.success([])
}
```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> {
return.success([])
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
return.failure(0)
}
```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> {
return.failure(0)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
// TODO: Implement me
}
```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> {
// TODO: Implement me
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
// TODO: Implement
}
```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> {
// TODO: Implement
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
// TODO: implement me
}
```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> {
// TODO: implement me
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
return.failure(0)
}
```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> {
return.failure(0)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
return.failure(0)
}
```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> {
return.failure(0)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
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> {
// TODO: Implement me!
return.failure(0)
}
```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> {
// TODO: Implement me!
return.failure(0)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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
}
```
// 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"
}
return isPrime(length)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```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"
}
return isPrime(length)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
return isPrime(length)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(length)? "YES" : "NO" // expected expression
return isPrime(length)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(length)? "YES" : "NO" // string literal is unused
return isPrime(length)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
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)
return (end - start + 1) % 2 == 0? "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 (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (end - start + 1) % 2 == 0? "YES" : "NO"
}
```
return (end - start + 1) % 2 == 0? "YES" : "NO" // string literal is unused
return (end - start + 1) % 2 == 0? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (end - start + 1) % 2 == 0? "YES" : "NO" // expected expression
return (end - start + 1) % 2 == 0? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Int'
return (end - start + 1) % 2 == 0? "YES" : "NO" // cannot convert return expression of type 'Bool' to return type 'String'
return (end - start + 1) % 2 == 0? "YES" : "NO" // consecutive statements on a line must be separated by ';'
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)
return (start...end).count.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 (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).count.isPrime? "YES" : "NO"
}
```
return (start...end).count.isPrime? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).count.isPrime? "YES" : "NO" // string literal is unused
return (start...end).count.isPrime? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).count.isPrime? "YES" : "NO" // expected expression
return (start...end).count.isPrime? "YES" : "NO" // type of expression is ambiguous without a type annotation
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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // string literal is unused
return isPrime(end - start + 1)? "YES" : "NO" // expected expression
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)
return (start...end).count % 2 == 1? "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 (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).count % 2 == 1? "YES" : "NO"
}
```
return (start...end).count % 2 == 1? "YES" : "NO" // expected expression
return (start...end).count % 2 == 1? "YES" : "NO" // string literal is unused
return (start...end).count % 2 == 1? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).count % 2 == 1? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).count % 2 == 1? "YES" : "NO" // cannot convert return expression of type 'Bool' to return type 'String'
return (start...end).count % 2 == 1? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Int'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```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
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // string literal is unused
return isPrime(end - start + 1)? "YES" : "NO" // expected expression
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)
return (start...end).count % 2 == 1? "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 (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).count % 2 == 1? "YES" : "NO"
}
```
return (start...end).count % 2 == 1? "YES" : "NO" // expected expression
return (start...end).count % 2 == 1? "YES" : "NO" // string literal is unused
return (start...end).count % 2 == 1? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).count % 2 == 1? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).count % 2 == 1? "YES" : "NO" // cannot convert return expression of type 'Bool' to return type 'String'
return (start...end).count % 2 == 1? "YES" : "NO" // cannot use optional chaining on non-optional value of 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)
if start > end {
return "NO"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // string literal is unused
return isPrime(end - start + 1)? "YES" : "NO" // expected expression
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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // string literal is unused
return isPrime(end - start + 1)? "YES" : "NO" // expected expression
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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```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"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // string literal is unused
return isPrime(end - start + 1)? "YES" : "NO" // expected expression
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var prod = 1
var sign = 1
for i in arr {
if i == 0 {
sign = 0
} else if i > 0 {
prod *= sign
} else {
sign = -sign
}
}
return prod * sign
}
```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? {
guard!arr.isEmpty else { return nil }
var prod = 1
var sign = 1
for i in arr {
if i == 0 {
sign = 0
} else if i > 0 {
prod *= sign
} else {
sign = -sign
}
}
return prod * sign
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
var sign = 1
for num in arr {
if num == 0 {
sign = 0
} else {
result *= sign
sign *= num > 0? 1 : -1
}
}
return result
}
```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? {
guard!arr.isEmpty else { return nil }
var result = 1
var sign = 1
for num in arr {
if num == 0 {
sign = 0
} else {
result *= sign
sign *= num > 0? 1 : -1
}
}
return result
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
sign *= num > 0? 1 : -1 // cannot convert value of type 'Bool' to expected argument type 'Int'
sign *= num > 0? 1 : -1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
sign *= num > 0? 1 : -1 // cannot use optional chaining on non-optional value of type 'Int'
sign *= num > 0? 1 : -1 // consecutive statements on a line must be separated by ';'
sign *= num > 0? 1 : -1 // expected expression
sign *= num > 0? 1 : -1 // integer literal is unused
sign *= num > 0? 1 : -1 // consecutive statements on a line must be separated by ';'
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod *= 0
} else {
prod *= i > 0? 1 : -1
}
sum += abs(i)
}
return prod * sum
}
```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? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod *= 0
} else {
prod *= i > 0? 1 : -1
}
sum += abs(i)
}
return prod * sum
}
```
prod *= i > 0? 1 : -1 // cannot use optional chaining on non-optional value of type 'Int'
prod *= i > 0? 1 : -1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
prod *= i > 0? 1 : -1 // consecutive statements on a line must be separated by ';'
prod *= i > 0? 1 : -1 // expected expression
prod *= i > 0? 1 : -1 // cannot convert value of type 'Bool' to expected argument type 'Int'
prod *= i > 0? 1 : -1 // consecutive statements on a line must be separated by ';'
prod *= i > 0? 1 : -1 // integer literal is unused
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var prod = 1
var sum = 0
for i in arr {
prod *= i < 0? -1 : 1
sum += abs(i)
}
return prod * sum
}
```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? {
guard!arr.isEmpty else { return nil }
var prod = 1
var sum = 0
for i in arr {
prod *= i < 0? -1 : 1
sum += abs(i)
}
return prod * sum
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
prod *= i < 0? -1 : 1 // expected expression
prod *= i < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
prod *= i < 0? -1 : 1 // cannot convert value of type 'Bool' to expected argument type 'Int'
prod *= i < 0? -1 : 1 // cannot use optional chaining on non-optional value of type 'Int'
prod *= i < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
prod *= i < 0? -1 : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
prod *= i < 0? -1 : 1 // integer literal is unused
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var result = 1
var sign = 1
for i in 0..<arr.count {
result *= sign
sign = arr[i] > 0? 1 : -1
}
return result
}
```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? {
guard arr.count > 0 else { return nil }
var result = 1
var sign = 1
for i in 0..<arr.count {
result *= sign
sign = arr[i] > 0? 1 : -1
}
return result
}
```
sign = arr[i] > 0? 1 : -1 // expected expression
sign = arr[i] > 0? 1 : -1 // cannot assign value of type 'Bool' to type 'Int'
sign = arr[i] > 0? 1 : -1 // cannot use optional chaining on non-optional value of type 'Int'
sign = arr[i] > 0? 1 : -1 // integer literal is unused
sign = arr[i] > 0? 1 : -1 // consecutive statements on a line must be separated by ';'
sign = arr[i] > 0? 1 : -1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
sign = arr[i] > 0? 1 : -1 // consecutive statements on a line must be separated by ';'
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod = 0
} else if i > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(i)
}
return prod * sum
}
```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? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod = 0
} else if i > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(i)
}
return prod * sum
}
```
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod *= 0
} else if i > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(i)
}
return prod * sum
}
```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? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod *= 0
} else if i > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(i)
}
return prod * sum
}
```
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for num in arr {
if num == 0 {
prod *= 0
} else if num > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(num)
}
return prod * sum
}
```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? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for num in arr {
if num == 0 {
prod *= 0
} else if num > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(num)
}
return prod * sum
}
```
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var result = 1
var sign = 1
for i in 0..<arr.count {
if arr[i] == 0 {
result = 0
break
}
if arr[i] < 0 {
sign *= -1
}
}
return result * sign
}
```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? {
guard arr.count > 0 else { return nil }
var result = 1
var sign = 1
for i in 0..<arr.count {
if arr[i] == 0 {
result = 0
break
}
if arr[i] < 0 {
sign *= -1
}
}
return result * sign
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod *= 0
} else if i > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(i)
}
return prod * sum
}
```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? {
guard arr.count > 0 else { return nil }
var prod = 1
var sum = 0
for i in arr {
if i == 0 {
prod *= 0
} else if i > 0 {
prod *= 1
} else {
prod *= -1
}
sum += abs(i)
}
return prod * sum
}
```
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var visited = Set<Int>()
var queue = [(Int, Int)]()
queue.append((0, 0))
visited.insert(0)
while!queue.isEmpty {
let (x, y) = queue.removeFirst()
if result.count == k {
break
}
if x == grid.count - 1 && y == grid.count - 1 {
result.append(grid[x][y])
break
}
if x + 1 < grid.count &&!visited.contains(grid[x + 1][y]) {
queue.append((x + 1, y))
visited.insert(grid[x + 1][y])
}
if y + 1 < grid.count &&!visited.contains(grid[x][y + 1]) {
queue.append((x, y + 1))
visited.insert(grid[x][y + 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 visited = Set<Int>()
var queue = [(Int, Int)]()
queue.append((0, 0))
visited.insert(0)
while!queue.isEmpty {
let (x, y) = queue.removeFirst()
if result.count == k {
break
}
if x == grid.count - 1 && y == grid.count - 1 {
result.append(grid[x][y])
break
}
if x + 1 < grid.count &&!visited.contains(grid[x + 1][y]) {
queue.append((x + 1, y))
visited.insert(grid[x + 1][y])
}
if y + 1 < grid.count &&!visited.contains(grid[x][y + 1]) {
queue.append((x, y + 1))
visited.insert(grid[x][y + 1])
}
}
return result
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
func minPath(grid: [[Int]], k: Int) -> [Int] {
var res = [Int]()
var visited = Set<Int>()
var queue = [(Int, Int)]()
queue.append((0, 0))
visited.insert(0)
while!queue.isEmpty {
let (x, y) = queue.removeFirst()
if res.count == k {
break
}
if x == grid.count - 1 && y == grid[0].count - 1 {
res.append(grid[x][y])
break
}
if x + 1 < grid.count &&!visited.contains(grid[x + 1][y]) {
queue.append((x + 1, y))
visited.insert(grid[x + 1][y])
}
if y + 1 < grid[0].count &&!visited.contains(grid[x][y + 1]) {
queue.append((x, y + 1))
visited.insert(grid[x][y + 1])
}
}
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] {
var res = [Int]()
var visited = Set<Int>()
var queue = [(Int, Int)]()
queue.append((0, 0))
visited.insert(0)
while!queue.isEmpty {
let (x, y) = queue.removeFirst()
if res.count == k {
break
}
if x == grid.count - 1 && y == grid[0].count - 1 {
res.append(grid[x][y])
break
}
if x + 1 < grid.count &&!visited.contains(grid[x + 1][y]) {
queue.append((x + 1, y))
visited.insert(grid[x + 1][y])
}
if y + 1 < grid[0].count &&!visited.contains(grid[x][y + 1]) {
queue.append((x, y + 1))
visited.insert(grid[x][y + 1])
}
}
return res
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
func minPath(grid: [[Int]], k: Int) -> [Int] {
// Write your code here.
}
```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] {
// Write your code here.
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
// Write your code here.
}
```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] {
// Write your code here.
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var visited = Set<Int>()
var queue = [(Int, Int)]()
queue.append((0, 0))
visited.insert(0)
while!queue.isEmpty {
let (x, y) = queue.removeFirst()
if result.count == k {
break
}
if x == grid.count - 1 && y == grid.count - 1 {
result.append(grid[x][y])
break
}
if x + 1 < grid.count &&!visited.contains(grid[x + 1][y]) {
queue.append((x + 1, y))
visited.insert(grid[x + 1][y])
}
if y + 1 < grid.count &&!visited.contains(grid[x][y + 1]) {
queue.append((x, y + 1))
visited.insert(grid[x][y + 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 visited = Set<Int>()
var queue = [(Int, Int)]()
queue.append((0, 0))
visited.insert(0)
while!queue.isEmpty {
let (x, y) = queue.removeFirst()
if result.count == k {
break
}
if x == grid.count - 1 && y == grid.count - 1 {
result.append(grid[x][y])
break
}
if x + 1 < grid.count &&!visited.contains(grid[x + 1][y]) {
queue.append((x + 1, y))
visited.insert(grid[x + 1][y])
}
if y + 1 < grid.count &&!visited.contains(grid[x][y + 1]) {
queue.append((x, y + 1))
visited.insert(grid[x][y + 1])
}
}
return result
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
func minPath(grid: [[Int]], k: Int) -> [Int] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
// Write your code here
}
```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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var visited = Set<Int>()
var path = [Int]()
var minPath = [Int]()
var minPathLength = Int.max
func dfs(_ row: Int, _ col: Int, _ length: Int) {
if length == k {
if length < minPathLength {
minPath = path
minPathLength = length
}
return
}
let index = row * grid[0].count + col
if visited.contains(index) {
return
}
visited.insert(index)
path.append(grid[row][col])
if row > 0 {
dfs(row - 1, col, length + 1)
}
if row < grid.count - 1 {
dfs(row + 1, col, length + 1)
}
if col > 0 {
dfs(row, col - 1, length + 1)
}
if col < grid[0].count - 1 {
dfs(row, col + 1, length + 1)
}
path.removeLast()
visited.remove(index)
}
dfs(0, 0, 0)
return minPath
}
```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 = Set<Int>()
var path = [Int]()
var minPath = [Int]()
var minPathLength = Int.max
func dfs(_ row: Int, _ col: Int, _ length: Int) {
if length == k {
if length < minPathLength {
minPath = path
minPathLength = length
}
return
}
let index = row * grid[0].count + col
if visited.contains(index) {
return
}
visited.insert(index)
path.append(grid[row][col])
if row > 0 {
dfs(row - 1, col, length + 1)
}
if row < grid.count - 1 {
dfs(row + 1, col, length + 1)
}
if col > 0 {
dfs(row, col - 1, length + 1)
}
if col < grid[0].count - 1 {
dfs(row, col + 1, length + 1)
}
path.removeLast()
visited.remove(index)
}
dfs(0, 0, 0)
return minPath
}
```
var result = [Int]() // initialization of variable 'result' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
var dp = Array(repeating: Array(repeating: 0, count: k + 1), count: n)
dp[0][0] = 1
for i in 0..<n {
for j in 0..<n {
for l in 1...k {
if dp[i][l - 1] > 0 {
dp[i][l] += grid[i][j]
}
}
}
}
var res = [Int]()
for i in 0..<n {
for j in 0..<n {
for l in 1...k {
if dp[i][l] > 0 {
res.append(grid[i][j])
}
}
}
}
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(repeating: Array(repeating: 0, count: k + 1), count: n)
dp[0][0] = 1
for i in 0..<n {
for j in 0..<n {
for l in 1...k {
if dp[i][l - 1] > 0 {
dp[i][l] += grid[i][j]
}
}
}
}
var res = [Int]()
for i in 0..<n {
for j in 0..<n {
for l in 1...k {
if dp[i][l] > 0 {
res.append(grid[i][j])
}
}
}
}
return res
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
var res = [Int]()
var visited = Set<Int>()
var path = [Int]()
var min = Int.max
var minPath = [Int]()
func dfs(_ i: Int, _ j: Int, _ k: Int) {
if k == 0 {
let sum = path.reduce(0, +)
if sum < min {
min = sum
minPath = path
}
return
}
if i < 0 || i >= grid.count || j < 0 || j >= grid[0].count || visited.contains(grid[i][j]) {
return
}
visited.insert(grid[i][j])
path.append(grid[i][j])
dfs(i - 1, j, k - 1)
dfs(i + 1, j, k - 1)
dfs(i, j - 1, k - 1)
dfs(i, j + 1, k - 1)
path.removeLast()
visited.remove(grid[i][j])
}
dfs(0, 0, k)
return minPath
}
```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 res = [Int]()
var visited = Set<Int>()
var path = [Int]()
var min = Int.max
var minPath = [Int]()
func dfs(_ i: Int, _ j: Int, _ k: Int) {
if k == 0 {
let sum = path.reduce(0, +)
if sum < min {
min = sum
minPath = path
}
return
}
if i < 0 || i >= grid.count || j < 0 || j >= grid[0].count || visited.contains(grid[i][j]) {
return
}
visited.insert(grid[i][j])
path.append(grid[i][j])
dfs(i - 1, j, k - 1)
dfs(i + 1, j, k - 1)
dfs(i, j - 1, k - 1)
dfs(i, j + 1, k - 1)
path.removeLast()
visited.remove(grid[i][j])
}
dfs(0, 0, k)
return minPath
}
```
var res = [Int]() // initialization of variable 'res' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3...n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3...n {
if i % 2 == 0 {
result.append(result[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, 2]
if n <= 2 {
return Array(result[0...n])
}
for i in 3...n {
if i % 2 == 0 {
result.append(result[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, 2]
if n <= 2 {
return Array(result[0...n])
}
for i in 3...n {
if i % 2 == 0 {
result.append(result[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 tribonacci = [1, 3, 2]
if n < 3 {
return Array(tribonacci[0..<n])
}
for i in 3..<n {
if i % 2 == 0 {
tribonacci.append(tribonacci[i / 2])
} else {
tribonacci.append(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i + 1])
}
}
return tribonacci
}
```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 tribonacci = [1, 3, 2]
if n < 3 {
return Array(tribonacci[0..<n])
}
for i in 3..<n {
if i % 2 == 0 {
tribonacci.append(tribonacci[i / 2])
} else {
tribonacci.append(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i + 1])
}
}
return tribonacci
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [Int]()
if n == 0 {
return result
}
result.append(1)
if n == 1 {
return result
}
result.append(3)
if n == 2 {
return result
}
var a = 1
var b = 3
var c = 2
for _ in 3..<n {
let temp = c
c = a + b + c
a = b
b = temp
}
result.append(c)
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 = [Int]()
if n == 0 {
return result
}
result.append(1)
if n == 1 {
return result
}
result.append(3)
if n == 2 {
return result
}
var a = 1
var b = 3
var c = 2
for _ in 3..<n {
let temp = c
c = a + b + c
a = b
b = temp
}
result.append(c)
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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 = [Int](repeating: 0, count: n + 1)
result[0] = 1
result[1] = 3
result[2] = 2
for i in 3..<n+1 {
if i % 2 == 0 {
result[i] = 1 + i / 2
} else {
result[i] = 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 = [Int](repeating: 0, count: n + 1)
result[0] = 1
result[1] = 3
result[2] = 2
for i in 3..<n+1 {
if i % 2 == 0 {
result[i] = 1 + i / 2
} else {
result[i] = 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, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[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, 2]
for i in 3..<n {
if i % 2 == 0 {
result.append(result[i / 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var tribonacci = [1, 3, 2]
if n < 3 {
return Array(tribonacci[0...n])
}
for i in 3...n {
if i % 2 == 0 {
tribonacci.append(tribonacci[i / 2])
} else {
tribonacci.append(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i + 1])
}
}
return tribonacci
}
```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 tribonacci = [1, 3, 2]
if n < 3 {
return Array(tribonacci[0...n])
}
for i in 3...n {
if i % 2 == 0 {
tribonacci.append(tribonacci[i / 2])
} else {
tribonacci.append(tribonacci[i - 1] + tribonacci[i - 2] + tribonacci[i + 1])
}
}
return tribonacci
}
```
// Fatal error: Index out of range
func digits(n: Int) -> Int {
var result = 0
var num = n
while num > 0 {
let digit = num % 10
if digit % 2!= 0 {
result = result * 10 + 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 = 0
var num = n
while num > 0 {
let digit = num % 10
if digit % 2!= 0 {
result = result * 10 + digit
}
num /= 10
}
return result
}
```
if digit % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 2!= 0 { // '=' must have consistent whitespace on both sides
if digit % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
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 digits(n: Int) -> Int {
return 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 {
return 0
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 0
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= 10
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 = 0
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= 10
result += digit
}
num /= 10
}
return result
}
```
// XCTAssertTrue failed
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 digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
let digit = n % 10
if digit % 2 == 1 {
result *= 10
result += digit
}
n /= 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 = 0
var n = n
while n > 0 {
let digit = n % 10
if digit % 2 == 1 {
result *= 10
result += digit
}
n /= 10
}
return result
}
```
// XCTAssertTrue failed
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 digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 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 number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
return n.description.filter { $0.isNumber }.compactMap { Int(String($0)) }.filter { $0 % 2 == 1 }.reduce(1, *)
}
```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 {
return n.description.filter { $0.isNumber }.compactMap { Int(String($0)) }.filter { $0 % 2 == 1 }.reduce(1, *)
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 0
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= 10
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 = 0
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= 10
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// 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.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// 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.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
// 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.removeLast()
}
}
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.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($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 { Int(ceil($0)) }.reduce(0, +)
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
return Int(lst.map { ceil($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 Int(lst.map { ceil($0) }.reduce(0, +))
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(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)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($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 { Int(ceil($0)) }.reduce(0, +)
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
// TODO: Write your code here
}
```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 {
// TODO: Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
// Your code goes here
}
```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 {
// Your code goes here
}
```
} // missing return in global function expected to return 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func canArrange(arr: [Int]) -> Int {
// TODO: Write your code here
}
```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 {
// TODO: Write your code here
}
```
} // missing return in global function expected to return 'Int'
func canArrange(arr: [Int]) -> Int {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func canArrange(arr: [Int]) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i - 1] {
result = i
break
}
}
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
break
}
}
return result
}
```
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
var i = 0
while i < arr.count {
if arr[i] > 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] > i + 1 {
result = i
break
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var largest = -1
for i in 0..<arr.count {
if arr[i] > largest {
largest = arr[i]
} else {
return i
}
}
return -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 largest = -1
for i in 0..<arr.count {
if arr[i] > largest {
largest = arr[i]
} else {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
var i = 0
while i < arr.count {
if arr[i] <= arr[i - 1] {
result = i
}
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
}
i += 1
}
return result
}
```
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var largest = -1
for i in 0..<arr.count {
if arr[i] > largest {
largest = arr[i]
} else {
return i
}
}
return -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 largest = -1
for i in 0..<arr.count {
if arr[i] > largest {
largest = arr[i]
} else {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count {
if arr[i] > arr[i-1] {
maxIndex = i
}
}
return maxIndex
}
```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 maxIndex = -1
for i in 0..<arr.count {
if arr[i] > arr[i-1] {
maxIndex = i
}
}
return maxIndex
}
```
// Fatal error: Index out of range
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largestNegative: Int? = nil
var smallestPositive: Int? = nil
for num in lst {
if num < 0 {
if largestNegative == nil || num > largestNegative! {
largestNegative = num
}
} else if num > 0 {
if smallestPositive == nil || num < smallestPositive! {
smallestPositive = num
}
}
}
return (largestNegative, smallestPositive)
}
```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 largestNegative: Int? = nil
var smallestPositive: Int? = nil
for num in lst {
if num < 0 {
if largestNegative == nil || num > largestNegative! {
largestNegative = num
}
} else if num > 0 {
if smallestPositive == nil || num < smallestPositive! {
smallestPositive = num
}
}
}
return (largestNegative, smallestPositive)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var a: Int? = nil
var b: Int? = 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)
}
```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: Int? = nil
var b: Int? = 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 largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negatives: [Int] = []
var positives: [Int] = []
for i in lst {
if i < 0 {
negatives.append(i)
} else if i > 0 {
positives.append(i)
}
}
if negatives.count > 0 {
return (negatives.max(), nil)
} else if positives.count > 0 {
return (nil, positives.min())
} else {
return (nil, nil)
}
}
```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 negatives: [Int] = []
var positives: [Int] = []
for i in lst {
if i < 0 {
negatives.append(i)
} else if i > 0 {
positives.append(i)
}
}
if negatives.count > 0 {
return (negatives.max(), nil)
} else if positives.count > 0 {
return (nil, positives.min())
} else {
return (nil, nil)
}
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negatives: [Int] = []
var positives: [Int] = []
for i in lst {
if i < 0 {
negatives.append(i)
} else if i > 0 {
positives.append(i)
}
}
if negatives.count > 0 {
return (negatives.max(), nil)
} else if positives.count > 0 {
return (nil, positives.min())
} else {
return (nil, nil)
}
}
```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 negatives: [Int] = []
var positives: [Int] = []
for i in lst {
if i < 0 {
negatives.append(i)
} else if i > 0 {
positives.append(i)
}
}
if negatives.count > 0 {
return (negatives.max(), nil)
} else if positives.count > 0 {
return (nil, positives.min())
} else {
return (nil, nil)
}
}
```
// 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)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int? = nil
var positive: Int? = nil
for i in lst {
if i < 0 {
if negative == nil || i > negative! {
negative = i
}
} else if i > 0 {
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?) {
var negative: Int? = nil
var positive: Int? = nil
for i in lst {
if i < 0 {
if negative == nil || i > negative! {
negative = i
}
} else if i > 0 {
if positive == nil || i < positive! {
positive = i
}
}
}
return (negative, positive)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int?
var positive: Int?
for i in lst {
if i < 0 {
negative = i
} else if i > 0 {
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?
var positive: Int?
for i in lst {
if i < 0 {
negative = i
} else if i > 0 {
positive = i
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int?
var positive: Int?
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?
var positive: Int?
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)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int?
var positive: Int?
for i in lst {
if i < 0 {
negative = i
} else if i > 0 {
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?
var positive: Int?
for i in lst {
if i < 0 {
negative = i
} else if i > 0 {
positive = i
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```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 largest: Int? = nil
var smallest: Int? = nil
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : 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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
// Create a function that takes two 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
// Create a function that takes two 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
// Create a function that takes two 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,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : b > a?.
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // expected expression
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case let (.doubleValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (a, b) where a > b:
return a
case let (a, b) where a < b:
return b
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (a, b) where a > b:
return a
case let (a, b) where a < b:
return b
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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case let (.doubleValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (a, b) where a > b:
return a
case let (a, b) where a < b:
return b
default:
return nil
}
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (a, b) where a > b:
return a
case let (a, b) where a < b:
return b
default:
return nil
}
}
// 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,
// compareFive(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFive(a:.intValue(1), b:.stringValue("2,
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
case let (a, b) where a > b: // binary operator '>' cannot be applied to two 'Value' operands
case let (a, b) where a < b: // binary operator '<' cannot be applied to two 'Value' operands
case let (a, b) where a > b: // binary operator '>' cannot be applied to two 'Value' operands
case let (a, b) where a < b: // binary operator '<' cannot be applied to two 'Value' operands
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareTwo(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareThree(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
```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? {
// TODO: Implement this function
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : 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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // integer literal is unused
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // integer literal is unused
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // integer literal is unused
let b = Double(b)?? 0 // integer literal is unused
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // integer literal is unused
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // integer literal is unused
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareTwo(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
```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? {
// TODO: Implement this function
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : 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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : 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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil
default:
return nil
}
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : a < b?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareTwo(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareThree(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareFour(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
func compareFive(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
```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? {
// TODO: Implement this function
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
// 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,
// compareFive(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFive(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFive(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFive(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFive(a: Value, b: Value) -> Value? {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
} // missing return in global function expected to return 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : 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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // integer literal is unused
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // integer literal is unused
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // integer literal is unused
let b = Double(b)?? 0 // integer literal is unused
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // integer literal is unused
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // integer literal is unused
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : 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, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) : a < b?.intValue(b) : nil
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil
case (.stringValue(let a),.stringValue(let b)):
let a = a.replacingOccurrences(of: ",", with: ".")
let b = b.replacingOccurrences(of: ",", with: ".")
let a = Double(a)?? 0
let b = Double(b)?? 0
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil
default:
return nil
}
}
// 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,
// compareFour(a:.intValue(1), b:.doubleValue
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // integer literal is unused
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // integer literal is unused
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // integer literal is unused
let b = Double(b)?? 0 // integer literal is unused
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // expected expression
return a > b?.intValue(a) : a < b?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : a < b?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : a < b?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // consecutive statements on a line must be separated by ';'
let a = Double(a)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let a = Double(a)?? 0 // integer literal is unused
let b = Double(b)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let b = Double(b)?? 0 // consecutive statements on a line must be separated by ';'
let b = Double(b)?? 0 // integer literal is unused
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return a > b?.stringValue(a.description) : a < b?.stringValue(b.description) : nil // expected expression
func isEqualToSumEven(n: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isEqualToSumEven(n: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isEqualToSumEven(n: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isEqualToSumEven(n: Int) -> Bool {
if n < 8 {
return false
}
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```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 {
if n < 8 {
return false
}
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isEqualToSumEven(n: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```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
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var result = false
for i in 2...n/2 {
for j in 2...n/2 {
for k in 2...n/2 {
for l in 2...n/2 {
if i + j + k + l == n && i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
result = true
}
}
}
}
}
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 result = false
for i in 2...n/2 {
for j in 2...n/2 {
for k in 2...n/2 {
for l in 2...n/2 {
if i + j + k + l == n && i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
result = true
}
}
}
}
}
return result
}
```
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
for j in 2...n {
for k in 2...n {
for l in 2...n {
if i + j + k + l == n && i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
sum += 1
}
}
}
}
}
return sum == 1
}
```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 2...n {
for j in 2...n {
for k in 2...n {
for l in 2...n {
if i + j + k + l == n && i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
sum += 1
}
}
}
}
}
return sum == 1
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```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
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
return n > 0? n * specialFactorial(n: n - 1) : 1
}
```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 {
return n > 0? n * specialFactorial(n: n - 1) : 1
}
```
return n > 0? n * specialFactorial(n: n - 1) : 1 // result of operator '*' is unused
return n > 0? n * specialFactorial(n: n - 1) : 1 // cannot convert return expression of type 'Bool' to return type 'Int'
return n > 0? n * specialFactorial(n: n - 1) : 1 // expected expression
return n > 0? n * specialFactorial(n: n - 1) : 1 // cannot use optional chaining on non-optional value of type 'Int'
return n > 0? n * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? n * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? n * specialFactorial(n: n - 1) : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func specialFactorial(n: Int) -> Int {
return n > 0? n * specialFactorial(n: n - 1) : 1
}
```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 {
return n > 0? n * specialFactorial(n: n - 1) : 1
}
```
return n > 0? n * specialFactorial(n: n - 1) : 1 // result of operator '*' is unused
return n > 0? n * specialFactorial(n: n - 1) : 1 // cannot convert return expression of type 'Bool' to return type 'Int'
return n > 0? n * specialFactorial(n: n - 1) : 1 // expected expression
return n > 0? n * specialFactorial(n: n - 1) : 1 // cannot use optional chaining on non-optional value of type 'Int'
return n > 0? n * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? n * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? n * specialFactorial(n: n - 1) : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func specialFactorial(n: Int) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
func specialFactorial(n: Int) -> Int {
return n > 0? n * specialFactorial(n: n - 1) : 1
}
```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 {
return n > 0? n * specialFactorial(n: n - 1) : 1
}
```
return n > 0? n * specialFactorial(n: n - 1) : 1 // result of operator '*' is unused
return n > 0? n * specialFactorial(n: n - 1) : 1 // cannot convert return expression of type 'Bool' to return type 'Int'
return n > 0? n * specialFactorial(n: n - 1) : 1 // expected expression
return n > 0? n * specialFactorial(n: n - 1) : 1 // cannot use optional chaining on non-optional value of type 'Int'
return n > 0? n * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? n * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? n * specialFactorial(n: n - 1) : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
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 {
return 0
}
```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 {
return 0
}
```
// 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 {
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1
}
```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 {
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1
}
```
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1 // consecutive statements on a line must be separated by ';'
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1 // cannot call value of non-function type 'Int'
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1 // cannot convert return expression of type 'Bool' to return type 'Int'
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1 // expected expression
return n > 0? (1...n).reduce(1, *) * specialFactorial(n: n - 1) : 1 // cannot use optional chaining on non-optional value of type 'Int'
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else {
result += "_"
}
count = 0
result += String(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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else {
result += "_"
}
count = 0
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result.append(char)
} else if count == 1 {
result.append("_")
result.append(char)
count = 0
} else {
result.append("-")
result.append(char)
count = 0
}
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result.append(char)
} else if count == 1 {
result.append("_")
result.append(char)
count = 0
} else {
result.append("-")
result.append(char)
count = 0
}
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result.append(char)
} else if count == 1 {
result.append("_")
result.append(char)
count = 0
} else if count > 1 {
result.append("-")
result.append(char)
count = 0
}
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result.append(char)
} else if count == 1 {
result.append("_")
result.append(char)
count = 0
} else if count > 1 {
result.append("-")
result.append(char)
count = 0
}
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
count = 0
}
if count == 0 {
result += String(char)
} else if count == 1 {
result += "_"
} else {
result += "-"
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
count = 0
}
if count == 0 {
result += String(char)
} else if count == 1 {
result += "_"
} else {
result += "-"
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
count = 0
}
if count == 0 {
result += String(char)
} else if count == 1 {
result += "_"
} else if count == 2 {
result += "-"
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
count = 0
}
if count == 0 {
result += String(char)
} else if count == 1 {
result += "_"
} else if count == 2 {
result += "-"
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result.append(char)
} else if count == 1 {
result.append("_")
result.append(char)
} else if count > 1 {
result.append("-")
result.append(char)
}
count = 0
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result.append(char)
} else if count == 1 {
result.append("_")
result.append(char)
} else if count > 1 {
result.append("-")
result.append(char)
}
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else {
result += "_"
}
count = 0
result += String(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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else {
result += "_"
}
count = 0
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last == " " {
result.removeLast()
result += "-"
} else {
result += "_"
}
} else {
result += String(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.removeLast()
result += "-"
} else {
result += "_"
}
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
result += String(char)
count = 0
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
result += String(char)
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result += String(char)
} else if count == 1 {
result += "_"
} else {
result += "-\(char)"
count = 0
}
}
}
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count == 0 {
result += String(char)
} else if count == 1 {
result += "_"
} else {
result += "-\(char)"
count = 0
}
}
}
return result
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
return "No"
}
```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 {
return "No"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
// TODO: Write your code here
}
```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 {
// TODO: Write your code here
}
```
} // missing return in global function expected to return 'String'
func fileNameCheck(fileName: String) -> String {
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 {
return "Yes"
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
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 {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
if number <= 3 {
return true
}
if number % 2 == 0 || number % 3 == 0 {
return false
}
var i = 5
while i * i <= number {
if number % i == 0 || number % (i + 2) == 0 {
return false
}
i += 6
}
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 {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
if number <= 3 {
return true
}
if number % 2 == 0 || number % 3 == 0 {
return false
}
var i = 5
while i * i <= number {
if number % i == 0 || number % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += "\(word) "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in 2..<n {
if n % 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 {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += "\(word) "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % 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 {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 { return false }
if n <= 3 { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
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 {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 { return false }
if n <= 3 { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
let primes = [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 result = ""
for word in words {
if primes.contains(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
```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.components(separatedBy: " ")
let primes = [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 result = ""
for word in words {
if primes.contains(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
let primes = [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 result = ""
for word in words {
if primes.contains(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
```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.components(separatedBy: " ")
let primes = [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 result = ""
for word in words {
if primes.contains(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [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 result = ""
for word in words {
if primes.contains(word.count) {
result += "\(word) "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
```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: " ")
let primes = [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 result = ""
for word in words {
if primes.contains(word.count) {
result += "\(word) "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
```
func simplify(x: String, n: String) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNum = Int(x[0])!
let xDen = Int(x[1])!
let nNum = Int(n[0])!
let nDen = Int(n[1])!
let xNumerator = xNum * nDen
let xDenominator = xDen * nNum
return xNumerator == xDenominator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNum = Int(x[0])!
let xDen = Int(x[1])!
let nNum = Int(n[0])!
let nDen = Int(n[1])!
let xNumerator = xNum * nDen
let xDenominator = xDen * nNum
return xNumerator == xDenominator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesN = xNumerator * nNumerator
let xDenominatorTimesN = xDenominator * nDenominator
return xNumeratorTimesN % xDenominatorTimesN == 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 xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesN = xNumerator * nNumerator
let xDenominatorTimesN = xDenominator * nDenominator
return xNumeratorTimesN % xDenominatorTimesN == 0
}
```
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(x[0])!
let xDenominator = Int(x[1])!
let nNumerator = Int(n[0])!
let nDenominator = Int(n[1])!
let xNumeratorTimesNNumerator = xNumerator * nNumerator
let xDenominatorTimesNDenominator = xDenominator * nDenominator
return xNumeratorTimesNNumerator == xDenominatorTimesNDenominator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/").map { Int($0)! }
let n = n.split(separator: "/").map { Int($0)! }
return x[0] * n[1] == x[1] * n[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 x = x.split(separator: "/").map { Int($0)! }
let n = n.split(separator: "/").map { Int($0)! }
return x[0] * n[1] == x[1] * n[0]
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(String(x[0]))!
let xDenominator = Int(String(x[1]))!
let nNumerator = Int(String(n[0]))!
let nDenominator = Int(String(n[1]))!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
return xNumeratorTimesNDenominator == xDenominatorTimesNNumerator
}
```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 x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNumerator = Int(String(x[0]))!
let xDenominator = Int(String(x[1]))!
let nNumerator = Int(String(n[0]))!
let nDenominator = Int(String(n[1]))!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
return xNumeratorTimesNDenominator == xDenominatorTimesNNumerator
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Int]'
func orderByPoints(nums: [Int]) -> [Int] {
// Your code goes here
}
```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] {
// Your code goes here
}
```
} // missing return in global function expected to return '[Int]'
func orderByPoints(nums: [Int]) -> [Int] {
// Your code here
}
```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] {
// Your code here
}
```
} // missing return in global function expected to return '[Int]'
func orderByPoints(nums: [Int]) -> [Int] {
// Your code goes here
}
```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] {
// Your code goes here
}
```
} // missing return in global function expected to return '[Int]'
func orderByPoints(nums: [Int]) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let a = $0.digits.reduce(0, +)
let b = $1.digits.reduce(0, +)
if a == b {
return $0 < $1
}
return a < b
}
}
```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 {
let a = $0.digits.reduce(0, +)
let b = $1.digits.reduce(0, +)
if a == b {
return $0 < $1
}
return a < b
}
}
```
let a = $0.digits.reduce(0, +) // value of type 'Int' has no member 'digits'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let a = abs($0)
let b = abs($1)
let aSum = a.digits.reduce(0, +)
let bSum = b.digits.reduce(0, +)
if aSum == bSum {
return $0 < $1
} else {
return aSum < bSum
}
}
}
extension Int {
var digits: [Int] {
var digits = [Int]()
var number = self
while number!= 0 {
digits.append(number % 10)
number /= 10
}
return digits
}
}
```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 {
let a = abs($0)
let b = abs($1)
let aSum = a.digits.reduce(0, +)
let bSum = b.digits.reduce(0, +)
if aSum == bSum {
return $0 < $1
} else {
return aSum < bSum
}
}
}
extension Int {
var digits: [Int] {
var digits = [Int]()
var number = self
while number!= 0 {
digits.append(number % 10)
number /= 10
}
return digits
}
}
```
while number!= 0 { // use of '=' in a boolean context, did you mean '=='?
while number!= 0 { // cannot force unwrap value of non-optional type 'Int'
while number!= 0 { // '=' must have consistent whitespace on both sides
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.digits.reduce(0, +)
let sum2 = $1.digits.reduce(0, +)
if sum1 == sum2 {
return $0 < $1
}
return sum1 < sum2
}
}
extension Int {
var digits: [Int] {
return String(self).compactMap { Int(String($0)) }
}
}
```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 {
let sum1 = $0.digits.reduce(0, +)
let sum2 = $1.digits.reduce(0, +)
if sum1 == sum2 {
return $0 < $1
}
return sum1 < sum2
}
}
extension Int {
var digits: [Int] {
return String(self).compactMap { Int(String($0)) }
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let a = abs($0)
let b = abs($1)
let aSum = a.description.map { Int(String($0))! }.reduce(0, +)
let bSum = b.description.map { Int(String($0))! }.reduce(0, +)
if aSum == bSum {
return $0 < $1
} else {
return aSum < bSum
}
}
}
```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 {
let a = abs($0)
let b = abs($1)
let aSum = a.description.map { Int(String($0))! }.reduce(0, +)
let bSum = b.description.map { Int(String($0))! }.reduce(0, +)
if aSum == bSum {
return $0 < $1
} else {
return aSum < bSum
}
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted { (a, b) -> Bool in
let aSum = a.digits.reduce(0, +)
let bSum = b.digits.reduce(0, +)
if aSum == bSum {
return a < b
}
return aSum < bSum
}
}
extension Int {
var digits: [Int] {
var digits = [Int]()
var num = self
while num > 0 {
digits.append(num % 10)
num /= 10
}
return digits
}
}
```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 { (a, b) -> Bool in
let aSum = a.digits.reduce(0, +)
let bSum = b.digits.reduce(0, +)
if aSum == bSum {
return a < b
}
return aSum < bSum
}
}
extension Int {
var digits: [Int] {
var digits = [Int]()
var num = self
while num > 0 {
digits.append(num % 10)
num /= 10
}
return digits
}
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'Int'
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
specialFilter(nums: [15, -73, 14, -15])
specialFilter(nums: [33, -2, -3, 45, 21, 109])
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
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
}
```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
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[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 a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[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 i+1...n {
for k in j+1...n {
if 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 i+1...n {
for k in j+1...n {
if i+j+k % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (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 i+1...n {
for k in j+1...n {
if (i+j+k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (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 i+1...n {
for k in j+1...n {
if (i+j+k)%3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (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 i+1...n {
for k in j+1...n {
if (i+j+k)%3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var a = [Int](repeating: 0, count: n)
for i in 0..<n {
a[i] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[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 a = [Int](repeating: 0, count: n)
for i in 0..<n {
a[i] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = [Int](repeating: 0, count: n)
var count = 0
for i in 0..<n {
a[i] = i * i - i + 1
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[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 a = [Int](repeating: 0, count: n)
var count = 0
for i in 0..<n {
a[i] = i * i - i + 1
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
for i in 0..<n {
for j in i + 1..<n {
for k in j + 1..<n {
if a[i] + a[j] + a[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
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
for i in 0..<n {
for j in i + 1..<n {
for k in j + 1..<n {
if a[i] + a[j] + a[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 i+1...n {
for k in j+1...n {
if (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 i+1...n {
for k in j+1...n {
if (i+j+k)%3 == 0 {
count += 1
}
}
}
}
return count
}
getMaxTriples(n: 5)
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var count = 0
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[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
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for item in lst {
if item.count % 2 == 0 {
result.append(item)
}
}
result.sort { $0.count < $1.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 = [String]()
for item in lst {
if item.count % 2 == 0 {
result.append(item)
}
}
result.sort { $0.count < $1.count }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
let sortedList = lst.filter { $0.count % 2 == 0 }.sorted { $0.count < $1.count }
return sortedList
}
```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] {
let sortedList = lst.filter { $0.count % 2 == 0 }.sorted { $0.count < $1.count }
return sortedList
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for item in lst {
if item.count % 2 == 0 {
result.append(item)
}
}
return result.sorted(by: { $0.count < $1.count })
}
```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 = [String]()
for item in lst {
if item.count % 2 == 0 {
result.append(item)
}
}
return result.sorted(by: { $0.count < $1.count })
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
return result.sorted(by: { $0.count < $1.count })
}
```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 = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
return result.sorted(by: { $0.count < $1.count })
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for word in lst {
if word.count % 2 == 0 {
result.append(word)
}
}
return result.sorted()
}
```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 = [String]()
for word in lst {
if word.count % 2 == 0 {
result.append(word)
}
}
return result.sorted()
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
result.sort(by: <)
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 = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
result.sort(by: <)
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
result.sort()
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 = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
result.sort()
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for item in lst {
if item.count % 2 == 0 {
result.append(item)
}
}
result.sort { $0.count < $1.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 = [String]()
for item in lst {
if item.count % 2 == 0 {
result.append(item)
}
}
result.sort { $0.count < $1.count }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
result.sort()
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 = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
result.sort()
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
return result.sorted(by: <)
}
```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 = [String]()
for i in lst {
if i.count % 2 == 0 {
result.append(i)
}
}
return result.sorted(by: <)
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func xOrY(n: Int, x: Int, y: Int) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for number in lst {
if number > 0 && number % 2!= 0 {
sum += Int(number * number)
}
}
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 number in lst {
if number > 0 && number % 2!= 0 {
sum += Int(number * number)
}
}
return sum
}
```
if number > 0 && number % 2!= 0 { // '=' must have consistent whitespace on both sides
if number > 0 && number % 2!= 0 { // cannot force unwrap value of non-optional type 'Double'
if number > 0 && number % 2!= 0 { // cannot convert value of type 'Double' to expected argument type 'Bool'
if number > 0 && number % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if number > 0 && number % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 2!= 0 {
sum += Int(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 && num % 2!= 0 {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 0 && num % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 0 && num % 2!= 0 { // cannot force unwrap value of non-optional type 'Double'
if num > 0 && num % 2!= 0 { // cannot convert value of type 'Double' to expected argument type 'Bool'
if num > 0 && num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 2!= 0 {
sum += Int(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 && num % 2!= 0 {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 0 && num % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 0 && num % 2!= 0 { // cannot force unwrap value of non-optional type 'Double'
if num > 0 && num % 2!= 0 { // cannot convert value of type 'Double' to expected argument type 'Bool'
if num > 0 && num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 2 == 1 {
sum += Int(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 && num % 2 == 1 {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 2 == 1 {
sum += Int(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 > 0 && i % 2 == 1 {
sum += Int(i * i)
}
}
return sum
}
```
if i > 0 && i % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 2!= 0 {
sum += Int(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 && num % 2!= 0 {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 0 && num % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 0 && num % 2!= 0 { // cannot force unwrap value of non-optional type 'Double'
if num > 0 && num % 2!= 0 { // cannot convert value of type 'Double' to expected argument type 'Bool'
if num > 0 && num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 2 == 1 {
sum += Int(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 && num % 2 == 1 {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 2) == 1 {
sum += Int(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 && num.truncatingRemainder(dividingBy: 2) == 1 {
sum += Int(num * num)
}
}
return sum
}
```
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 2) == 1 {
sum += Int(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 && num.truncatingRemainder(dividingBy: 2) == 1 {
sum += Int(num * num)
}
}
return sum
}
```
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 2 == 1 {
sum += Int(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 && num % 2 == 1 {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder 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] {
return game.enumerated().map { (index, element) in
return abs(element - guess[index])
}
}
```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.enumerated().map { (index, element) in
return abs(element - guess[index])
}
}
```
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] {
return game.enumerated().map { index, value in
abs(value - guess[index])
}
}
```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.enumerated().map { index, value in
abs(value - guess[index])
}
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { index, score in
abs(score - guess[index])
}
}
```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.enumerated().map { index, score in
abs(score - guess[index])
}
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { index, score in
return abs(score - guess[index])
}
}
```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.enumerated().map { index, score in
return abs(score - guess[index])
}
}
```
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 compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { index, score in
abs(score - guess[index])
}
}
```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.enumerated().map { index, score in
abs(score - guess[index])
}
}
```
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongest = extensions[0]
var strongestStrength = 0.0
for extension in extensions {
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count)
if strength > strongestStrength {
strongest = extension
strongestStrength = strength
}
}
return "\(className.lowercased().replacingOccurrences(of: " ", with: "_")).\(strongest.lowercased().replacingOccurrences(of: " ", with: "_"))"
}
```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 strongest = extensions[0]
var strongestStrength = 0.0
for extension in extensions {
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count)
if strength > strongestStrength {
strongest = extension
strongestStrength = strength
}
}
return "\(className.lowercased().replacingOccurrences(of: " ", with: "_")).\(strongest.lowercased().replacingOccurrences(of: " ", with: "_"))"
}
```
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
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count) // expected type name in extension declaration
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count) // declaration is only valid at file scope
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count) // expected '{' in extension
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count) // expected expression in list of expressions
let strength = Double(extension.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(extension.lowercased().filter { $0 >= "a" && $0 <= "z" }.count) // consecutive statements on a line must be separated by ';'
strongest = extension // expected expression in assignment
strongest = extension // declaration is only valid at file scope
strongestStrength = strength // cannot find type 'strongestStrength' in scope
strongestStrength = strength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension: String = ""
var strongestStrength: Double = 0.0
for extension in extensions {
let strength = calculateStrength(extension: extension)
if strength > strongestStrength {
strongestExtension = extension
strongestStrength = strength
}
}
return "\(className).\(strongestExtension)"
}
func calculateStrength(extension: String) -> Double {
var strength: Double = 0.0
for char in extension {
if char.isUppercase {
strength += 1.0
} else {
strength -= 1.0
}
}
return strength
}
```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 strongestExtension: String = ""
var strongestStrength: Double = 0.0
for extension in extensions {
let strength = calculateStrength(extension: extension)
if strength > strongestStrength {
strongestExtension = extension
strongestStrength = strength
}
}
return "\(className).\(strongestExtension)"
}
func calculateStrength(extension: String) -> Double {
var strength: Double = 0.0
for char in extension {
if char.isUppercase {
strength += 1.0
} else {
strength -= 1.0
}
}
return strength
}
```
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
let strength = calculateStrength(extension: extension) // declaration is only valid at file scope
let strength = calculateStrength(extension: extension) // consecutive statements on a line must be separated by ';'
let strength = calculateStrength(extension: extension) // expected type name in extension declaration
let strength = calculateStrength(extension: extension) // missing argument for parameter 'extension' in call
let strength = calculateStrength(extension: extension) // expected expression in list of expressions
let strength = calculateStrength(extension: extension) // expected '{' in extension
strongestExtension = extension // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestStrength = strength // expected '{' in extension
strongestStrength = strength // cannot find type 'strongestStrength' in scope
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestStrength = 0.0
for extension in extensions {
let strength = getStrength(extension)
if strength > strongestStrength {
strongestStrength = strength
strongestExtension = extension
}
}
return "\(className.lowercased()).\(strongestExtension)"
}
func getStrength(_ extension: String) -> Double {
var strength = 0.0
for char in extension {
if char.isUppercase {
strength += 1
} else {
strength -= 1
}
}
return strength
}
```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 strongestExtension = ""
var strongestStrength = 0.0
for extension in extensions {
let strength = getStrength(extension)
if strength > strongestStrength {
strongestStrength = strength
strongestExtension = extension
}
}
return "\(className.lowercased()).\(strongestExtension)"
}
func getStrength(_ extension: String) -> Double {
var strength = 0.0
for char in extension {
if char.isUppercase {
strength += 1
} else {
strength -= 1
}
}
return strength
}
```
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
let strength = getStrength(extension) // expected '{' in extension
let strength = getStrength(extension) // expected expression in list of expressions
let strength = getStrength(extension) // declaration is only valid at file scope
let strength = getStrength(extension) // missing argument for parameter #1 in call
let strength = getStrength(extension) // consecutive statements on a line must be separated by ';'
let strength = getStrength(extension) // expected type name in extension declaration
strongestExtension = extension // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtension = extension // expected '{' in extension
} // expected type name in extension declaration
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
func Strongest_Extension(className: String, extensions: [String]) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongest = extensions[0]
var strongestStrength = strength(strongest)
for ext in extensions {
let strength = strength(ext)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return className + "." + strongest
}
func strength(_ ext: String) -> Int {
var cap = 0
var sm = 0
for char in ext {
if char.isUppercase {
cap += 1
} else {
sm += 1
}
}
return cap - sm
}
```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 strongest = extensions[0]
var strongestStrength = strength(strongest)
for ext in extensions {
let strength = strength(ext)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return className + "." + strongest
}
func strength(_ ext: String) -> Int {
var cap = 0
var sm = 0
for char in ext {
if char.isUppercase {
cap += 1
} else {
sm += 1
}
}
return cap - sm
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongest = extensions[0]
var strongestStrength = 0.0
for ext in extensions {
let strength = Double(ext.uppercased().filter { $0.isUppercase }.count) - Double(ext.lowercased().filter { $0.isLowercase }.count)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return "\(className.lowercased().replacingOccurrences(of: " ", with: "_")).\(strongest.lowercased().replacingOccurrences(of: " ", with: "_"))"
}
```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 strongest = extensions[0]
var strongestStrength = 0.0
for ext in extensions {
let strength = Double(ext.uppercased().filter { $0.isUppercase }.count) - Double(ext.lowercased().filter { $0.isLowercase }.count)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return "\(className.lowercased().replacingOccurrences(of: " ", with: "_")).\(strongest.lowercased().replacingOccurrences(of: " ", with: "_"))"
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongest = extensions[0]
var strongestStrength = 0.0
for ext in extensions {
let strength = Double(ext.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(ext.lowercased().filter { $0 >= "a" && $0 <= "z" }.count)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return "\(className).\(strongest)"
}
```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 strongest = extensions[0]
var strongestStrength = 0.0
for ext in extensions {
let strength = Double(ext.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(ext.lowercased().filter { $0 >= "a" && $0 <= "z" }.count)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return "\(className).\(strongest)"
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongest = ""
var strongestStrength = 0.0
for ext in extensions {
let strength = Double(ext.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(ext.lowercased().filter { $0 >= "a" && $0 <= "z" }.count)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return "\(className.lowercased().replacingOccurrences(of: " ", with: "_")).\(strongest.lowercased().replacingOccurrences(of: " ", with: "_"))"
}
```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 strongest = ""
var strongestStrength = 0.0
for ext in extensions {
let strength = Double(ext.uppercased().filter { $0 >= "A" && $0 <= "Z" }.count) - Double(ext.lowercased().filter { $0 >= "a" && $0 <= "z" }.count)
if strength > strongestStrength {
strongest = ext
strongestStrength = strength
}
}
return "\(className.lowercased().replacingOccurrences(of: " ", with: "_")).\(strongest.lowercased().replacingOccurrences(of: " ", with: "_"))"
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let b = b.map { String($0) }
for i in 0..<b.count {
if a.contains(b[i...]) {
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 {
let b = b.map { String($0) }
for i in 0..<b.count {
if a.contains(b[i...]) {
return true
}
}
return false
}
```
if a.contains(b[i...]) { // instance method 'contains' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func cycpatternCheck(a: String, b: String) -> Bool {
guard a.count >= b.count else { return false }
let bCount = b.count
let bArray = Array(b)
for i in 0..<a.count {
if a[a.index(a.startIndex, offsetBy: i)] == bArray[0] {
let aArray = Array(a)
var j = 0
while j < bCount {
if aArray[a.index(a.startIndex, offsetBy: i + j)]!= bArray[j] {
break
}
j += 1
}
if j == bCount {
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 {
guard a.count >= b.count else { return false }
let bCount = b.count
let bArray = Array(b)
for i in 0..<a.count {
if a[a.index(a.startIndex, offsetBy: i)] == bArray[0] {
let aArray = Array(a)
var j = 0
while j < bCount {
if aArray[a.index(a.startIndex, offsetBy: i + j)]!= bArray[j] {
break
}
j += 1
}
if j == bCount {
return true
}
}
}
return false
}
```
if aArray[a.index(a.startIndex, offsetBy: i + j)]!= bArray[j] { // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
if aArray[a.index(a.startIndex, offsetBy: i + j)]!= bArray[j] { // '=' must have consistent whitespace on both sides
if aArray[a.index(a.startIndex, offsetBy: i + j)]!= bArray[j] { // cannot convert value of type 'String.Index' to expected argument type 'Int'
if aArray[a.index(a.startIndex, offsetBy: i + j)]!= bArray[j] { // use of '=' in a boolean context, did you mean '=='?
func cycpatternCheck(a: String, b: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
for _ in 0..<b.count {
if a.contains(b) {
return true
}
b.append(b.removeFirst())
}
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 b = b
for _ in 0..<b.count {
if a.contains(b) {
return true
}
b.append(b.removeFirst())
}
return false
}
```
func cycpatternCheck(a: String, b: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var a = a
var b = b
for _ in 0..<a.count {
if a.contains(b) {
return true
}
a.append(a.removeFirst())
}
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 a = a
var b = b
for _ in 0..<a.count {
if a.contains(b) {
return true
}
a.append(a.removeFirst())
}
return false
}
```
var b = b // variable 'b' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var a = a
var b = b
var count = 0
while count < a.count {
if a.contains(b) {
return true
}
a.append(a.removeFirst())
count += 1
}
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 a = a
var b = b
var count = 0
while count < a.count {
if a.contains(b) {
return true
}
a.append(a.removeFirst())
count += 1
}
return false
}
```
var b = b // variable 'b' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let b = b.reversed()
return a.contains(b)
}
```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 {
let b = b.reversed()
return a.contains(b)
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
return a.contains(b) || a.contains(b.reversed())
}
```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 {
return a.contains(b) || a.contains(b.reversed())
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 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 num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num!= 0 {
if num % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 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 num = num
while num!= 0 {
if num % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 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 num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```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 evenCount = 0
var oddCount = 0
var num = num
while num!= 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func intToMiniRoman(number: Int) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func intToMiniRoman(number: Int) -> String {
// Your code here
}
```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 {
// Your code here
}
```
} // missing return in global function expected to return 'String'
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1] // variable 'roman' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1] // variable 'roman' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1] // variable 'roman' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
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
}
```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 >= 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
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
let roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1] // variable 'roman' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1] // variable 'roman' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
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
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1]
for (key, value) in roman {
while num >= value {
result += key
num -= value
}
}
return result
}
```
var roman = ["M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1] // variable 'roman' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return 'Bool'
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
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)
}
```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)
}
```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 {
let sides = [a, b, c]
let sortedSides = sides.sorted()
return sortedSides[0] * sortedSides[0] + sortedSides[1] * sortedSides[1] == sortedSides[2] * sortedSides[2]
}
```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 sides = [a, b, c]
let sortedSides = sides.sorted()
return sortedSides[0] * sortedSides[0] + sortedSides[1] * sortedSides[1] == sortedSides[2] * sortedSides[2]
}
```
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 {
if a > 0 && b > 0 && c > 0 {
if a*a + b*b == c*c || a*a + c*c == b*b || b*b + c*c == a*a {
return true
}
}
return false
}
```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 {
if a > 0 && b > 0 && c > 0 {
if a*a + b*b == c*c || a*a + c*c == b*b || b*b + c*c == a*a {
return true
}
}
return 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
}
```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)
}
```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 findMax(words: [String]) -> String {
var maxWord = ""
var maxCount = 0
for word in words {
var count = 0
var unique = Set<Character>()
for char in word {
if!unique.contains(char) {
unique.insert(char)
count += 1
}
}
if count > maxCount {
maxWord = word
maxCount = count
}
}
return maxWord
}
```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 maxWord = ""
var maxCount = 0
for word in words {
var count = 0
var unique = Set<Character>()
for char in word {
if!unique.contains(char) {
unique.insert(char)
count += 1
}
}
if count > maxCount {
maxWord = word
maxCount = count
}
}
return maxWord
}
```
if!unique.contains(char) { // expected expression, var, or let in 'if' condition
func findMax(words: [String]) -> String {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'String'
func findMax(words: [String]) -> String {
var max = ""
for word in words {
if max.count < word.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 {
if max.count < word.count {
max = word
}
}
return max
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > maxCount {
maxCount = 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 = ""
var maxCount = 0
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > maxCount {
maxCount = count
max = word
}
}
return max
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var unique = Set<Character>()
for char in word {
unique.insert(char)
}
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```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 maxWord = ""
for word in words {
var unique = Set<Character>()
for char in word {
unique.insert(char)
}
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
for word in words {
if max.count < word.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 {
if max.count < word.count {
max = word
}
}
return max
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
if Set(word).count > max {
max = Set(word).count
maxWord = word
}
}
return maxWord
}
```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 maxWord = ""
for word in words {
if Set(word).count > max {
max = Set(word).count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
let count = Set(word).count
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 {
let count = Set(word).count
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var maxWord = ""
var maxCount = 0
for word in words {
var count = 0
for char in word {
if word.filter({$0 == char}).count == 1 {
count += 1
}
}
if count > maxCount {
maxWord = word
maxCount = count
}
}
return maxWord
}
```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 maxWord = ""
var maxCount = 0
for word in words {
var count = 0
for char in word {
if word.filter({$0 == char}).count == 1 {
count += 1
}
}
if count > maxCount {
maxWord = word
maxCount = count
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
if Set(word).count > max {
max = Set(word).count
maxWord = word
}
}
return maxWord
}
```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 maxWord = ""
for word in words {
if Set(word).count > max {
max = Set(word).count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```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] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var result = [Int]()
if need > remaining {
result.append(number + remaining)
result.append(0)
} else {
result.append(number + need)
result.append(remaining - need)
}
return result
}
```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 result = [Int]()
if need > remaining {
result.append(number + remaining)
result.append(0)
} else {
result.append(number + need)
result.append(remaining - need)
}
return result
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var left = remaining
if eaten + left >= need {
eaten += need
left -= need
} else {
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
if eaten + left >= need {
eaten += need
left -= need
} else {
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 - need
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 - need
return [eaten, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```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] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + remaining
var left = 0
if total >= need {
total = need
left = total - number
} else {
left = total - number
total = need
}
return [total, 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 total = number + remaining
var left = 0
if total >= need {
total = need
left = total - number
} else {
left = total - number
total = need
}
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var result = [Int]()
var total = number + remaining
if total >= need {
result.append(total)
result.append(total - need)
} else {
result.append(total)
result.append(0)
}
return result
}
```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 result = [Int]()
var total = number + remaining
if total >= need {
result.append(total)
result.append(total - need)
} else {
result.append(total)
result.append(0)
}
return result
}
```
var total = number + remaining // variable 'total' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var result = [Int]()
var total = number + remaining
if total >= need {
result.append(total)
result.append(total - need)
} else {
result.append(total)
result.append(0)
}
return result
}
```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 result = [Int]()
var total = number + remaining
if total >= need {
result.append(total)
result.append(total - need)
} else {
result.append(total)
result.append(0)
}
return result
}
```
var total = number + remaining // variable 'total' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result /= operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
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 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result /= operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i+1]
case "-":
result -= operands[i+1]
case "*":
result *= operands[i+1]
case "//":
result /= operands[i+1]
case "**":
result = Int(pow(Double(result), Double(operands[i+1])))
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 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i+1]
case "-":
result -= operands[i+1]
case "*":
result *= operands[i+1]
case "//":
result /= operands[i+1]
case "**":
result = Int(pow(Double(result), Double(operands[i+1])))
default:
break
}
}
return result
}
doAlgebra(operators: ["+", "*", "-"], operands: [2, 3, 4, 5])
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i+1]
case "-":
result -= operands[i+1]
case "*":
result *= operands[i+1]
case "//":
result /= operands[i+1]
case "**":
result = Int(pow(Double(result), Double(operands[i+1])))
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 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i+1]
case "-":
result -= operands[i+1]
case "*":
result *= operands[i+1]
case "//":
result /= operands[i+1]
case "**":
result = Int(pow(Double(result), Double(operands[i+1])))
default:
break
}
}
return result
}
doAlgebra(operators: ["+", "*", "-"], operands: [2, 3, 4, 5])
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
if operators[i] == "+" {
result += operands[i+1]
} else if operators[i] == "-" {
result -= operands[i+1]
} else if operators[i] == "*" {
result *= operands[i+1]
} else if operators[i] == "//" {
result /= operands[i+1]
} else if operators[i] == "**" {
result = Int(pow(Double(result), Double(operands[i+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 0..<operators.count {
if operators[i] == "+" {
result += operands[i+1]
} else if operators[i] == "-" {
result -= operands[i+1]
} else if operators[i] == "*" {
result *= operands[i+1]
} else if operators[i] == "//" {
result /= operands[i+1]
} else if operators[i] == "**" {
result = Int(pow(Double(result), Double(operands[i+1])))
}
}
return result
}
doAlgebra(operators: ["+", "*", "-"], operands: [2, 3, 4, 5])
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
if operators[i] == "+" {
result += operands[i+1]
} else if operators[i] == "-" {
result -= operands[i+1]
} else if operators[i] == "*" {
result *= operands[i+1]
} else if operators[i] == "//" {
result /= operands[i+1]
} else if operators[i] == "**" {
result = Int(pow(Double(result), Double(operands[i+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 0..<operators.count {
if operators[i] == "+" {
result += operands[i+1]
} else if operators[i] == "-" {
result -= operands[i+1]
} else if operators[i] == "*" {
result *= operands[i+1]
} else if operators[i] == "//" {
result /= operands[i+1]
} else if operators[i] == "**" {
result = Int(pow(Double(result), Double(operands[i+1])))
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
result = operate(result, operands[i], operators[i-1])
}
return result
}
func operate(_ a: Int, _ b: Int, _ op: String) -> Int {
switch op {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "//":
return a / b
case "**":
return a ^ b
default:
return 0
}
}
```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 {
result = operate(result, operands[i], operators[i-1])
}
return result
}
func operate(_ a: Int, _ b: Int, _ op: String) -> Int {
switch op {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "//":
return a / b
case "**":
return a ^ b
default:
return 0
}
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i+1]
case "-":
result -= operands[i+1]
case "*":
result *= operands[i+1]
case "//":
result /= operands[i+1]
case "**":
result = Int(pow(Double(result), Double(operands[i+1])))
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 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i+1]
case "-":
result -= operands[i+1]
case "*":
result *= operands[i+1]
case "//":
result /= operands[i+1]
case "**":
result = Int(pow(Double(result), Double(operands[i+1])))
default:
break
}
}
return result
}
doAlgebra(operators: ["+", "*", "-"], operands: [2, 3, 4, 5])
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result /= operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
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 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result /= operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
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 = Int(pow(Double(result), Double(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 = Int(pow(Double(result), Double(operands[i])))
}
}
return result
}
doAlgebra(operators: ["+", "*", "-"], operands: [2, 3, 4, 5])
```
// XCTAssertTrue failed
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 = Int(pow(Double(result), Double(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 = Int(pow(Double(result), Double(operands[i])))
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(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 {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // expected ',' separator
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // no exact matches in call to instance method 'append'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(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 {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(char)
}
}
return result
}
```
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // result of call to 'lowercased()' is unused
result += char.isUppercase? char.lowercased() : char.uppercased() // expected expression
result += char.isUppercase? char.lowercased() : char.uppercased() // cannot use optional chaining on non-optional value of type 'Bool'
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // binary operator '+=' cannot be applied to operands of type 'String' and 'Bool?'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(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 {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(char)
}
}
return result
}
```
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // result of call to 'lowercased()' is unused
result += char.isUppercase? char.lowercased() : char.uppercased() // expected expression
result += char.isUppercase? char.lowercased() : char.uppercased() // cannot use optional chaining on non-optional value of type 'Bool'
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // binary operator '+=' cannot be applied to operands of type 'String' and 'Bool?'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(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 {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // expected ',' separator
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // no exact matches in call to instance method 'append'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(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 {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(char)
}
}
return result
}
```
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // result of call to 'lowercased()' is unused
result += char.isUppercase? char.lowercased() : char.uppercased() // expected expression
result += char.isUppercase? char.lowercased() : char.uppercased() // cannot use optional chaining on non-optional value of type 'Bool'
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // binary operator '+=' cannot be applied to operands of type 'String' and 'Bool?'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(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 {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // expected ',' separator
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // no exact matches in call to instance method 'append'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(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 {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // expected ',' separator
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // no exact matches in call to instance method 'append'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(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 {
result.append(char.isUppercase? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // expected ',' separator
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
result.append(char.isUppercase? char.lowercased() : char.uppercased()) // no exact matches in call to instance method 'append'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(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 {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(char)
}
}
return result
}
```
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // result of call to 'lowercased()' is unused
result += char.isUppercase? char.lowercased() : char.uppercased() // expected expression
result += char.isUppercase? char.lowercased() : char.uppercased() // cannot use optional chaining on non-optional value of type 'Bool'
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // binary operator '+=' cannot be applied to operands of type 'String' and 'Bool?'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(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 {
result += char.isUppercase? char.lowercased() : char.uppercased()
} else {
result += String(char)
}
}
return result
}
```
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // result of call to 'lowercased()' is unused
result += char.isUppercase? char.lowercased() : char.uppercased() // expected expression
result += char.isUppercase? char.lowercased() : char.uppercased() // cannot use optional chaining on non-optional value of type 'Bool'
result += char.isUppercase? char.lowercased() : char.uppercased() // consecutive statements on a line must be separated by ';'
result += char.isUppercase? char.lowercased() : char.uppercased() // binary operator '+=' cannot be applied to operands of type 'String' and 'Bool?'
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.reduce("") { $0 + String(format: "%02x", $1) }
}
```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? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.reduce("") { $0 + String(format: "%02x", $1) }
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
_ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
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 = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
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 = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
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: [Int] = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
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 = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
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 = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
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: [Int] = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
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 = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 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 = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 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 = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
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: [Int] = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound