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 {
// TODO: Implement this function
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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in 0..<numbers.count {
if i != j {
let distance = abs(numbers[i] - numbers[j])
if distance <= 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 0..<numbers.count {
if i != j {
let distance = abs(numbers[i] - numbers[j])
if distance <= threshold {
return true
}
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
// TODO: Implement this function.
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 {
// TODO: Implement this function.
return false
}
```
// XCTAssertTrue failed
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sortedNumbers = numbers.sorted()
for (index, value) in sortedNumbers.enumerated() {
if index + 1 == sortedNumbers.count {
break
}
let nextValue = sortedNumbers[index + 1]
if abs(value - nextValue) <= 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 sortedNumbers = numbers.sorted()
for (index, value) in sortedNumbers.enumerated() {
if index + 1 == sortedNumbers.count {
break
}
let nextValue = sortedNumbers[index + 1]
if abs(value - nextValue) <= threshold {
return true
}
}
return false
}
```
var sortedNumbers = numbers.sorted() // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sortedNumbers = numbers.sorted()
for i in 0 ..< sortedNumbers.count - 1 {
let distance = sortedNumbers[i + 1] - sortedNumbers[i]
if distance < 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 {
let sortedNumbers = numbers.sorted()
for i in 0 ..< sortedNumbers.count - 1 {
let distance = sortedNumbers[i + 1] - sortedNumbers[i]
if distance < threshold {
return true
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i + 1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i + 1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var minDiff = threshold
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = numbers[j] - numbers[i]
if diff < minDiff {
minDiff = diff
}
}
}
return minDiff < 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 minDiff = threshold
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = numbers[j] - numbers[i]
if diff < minDiff {
minDiff = diff
}
}
}
return minDiff < threshold
}
```
// XCTAssertTrue failed
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var i = 1
while i < sorted.count {
if sorted[i] - sorted[i - 1] < threshold {
return true
}
i += 1
}
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 {
let sorted = numbers.sorted()
var i = 1
while i < sorted.count {
if sorted[i] - sorted[i - 1] < threshold {
return true
}
i += 1
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sortedNumbers = numbers.sorted()
var previousNumber = sortedNumbers[0]
for number in sortedNumbers[1..<sortedNumbers.count] {
if number - previousNumber < threshold {
return true
}
previousNumber = number
}
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 {
let sortedNumbers = numbers.sorted()
var previousNumber = sortedNumbers[0]
for number in sortedNumbers[1..<sortedNumbers.count] {
if number - previousNumber < threshold {
return true
}
previousNumber = number
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [String]()
var currentString = String()
for char in parenString {
if char == "(" {
if currentString.isEmpty {
currentString += "("
} else {
stack.append(currentString)
currentString = "("
}
} else if char == ")" {
currentString += ")"
if let lastStackItem = stack.popLast() {
result.append(lastStackItem + currentString)
currentString = String()
} else {
result.append(currentString)
currentString = String()
}
}
}
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 currentString = String()
for char in parenString {
if char == "(" {
if currentString.isEmpty {
currentString += "("
} else {
stack.append(currentString)
currentString = "("
}
} else if char == ")" {
currentString += ")"
if let lastStackItem = stack.popLast() {
result.append(lastStackItem + currentString)
currentString = String()
} else {
result.append(currentString)
currentString = String()
}
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [Character]()
var start = 0
for (index, char) in parenString.enumerated() {
if char == "(" {
stack.append(char)
} else if char == ")" {
stack.removeLast()
if stack.isEmpty {
result.append(String(parenString[parenString.index(parenString.startIndex, offsetBy: start)...parenString.index(parenString.startIndex, offsetBy: index)]))
start = index + 1
}
}
}
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 = [Character]()
var start = 0
for (index, char) in parenString.enumerated() {
if char == "(" {
stack.append(char)
} else if char == ")" {
stack.removeLast()
if stack.isEmpty {
result.append(String(parenString[parenString.index(parenString.startIndex, offsetBy: start)...parenString.index(parenString.startIndex, offsetBy: index)]))
start = index + 1
}
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var parenString = parenString
var groups = [String]()
while parenString.contains("(") {
let index = parenString.firstIndex(of: "(")!
let endIndex = parenString.lastIndex(of: ")")!
let group = parenString.prefix(upTo: endIndex + 1)
groups.append(String(group))
parenString.removeSubrange(index...endIndex)
}
return groups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var parenString = parenString
var groups = [String]()
while parenString.contains("(") {
let index = parenString.firstIndex(of: "(")!
let endIndex = parenString.lastIndex(of: ")")!
let group = parenString.prefix(upTo: endIndex + 1)
groups.append(String(group))
parenString.removeSubrange(index...endIndex)
}
return groups
}
```
let group = parenString.prefix(upTo: endIndex + 1) // binary operator '+' cannot be applied to operands of type 'String.Index' and 'Int'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [Character]()
for c in parenString {
if c == "(" {
stack.append(c)
current.append(c)
} else if c == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
current.append(c)
if stack.count == 0 {
result.append(current)
current = ""
}
}
}
if stack.count > 0 {
return []
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [Character]()
for c in parenString {
if c == "(" {
stack.append(c)
current.append(c)
} else if c == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
current.append(c)
if stack.count == 0 {
result.append(current)
current = ""
}
}
}
if stack.count > 0 {
return []
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [Character]()
var current = ""
for char in parenString where char != " " {
if char == "(" {
if !stack.isEmpty {
current += String(char)
}
stack.append(char)
} else if char == ")" {
if stack.last == "(" {
stack.removeLast()
}
if stack.isEmpty {
result.append(current)
current = ""
} else {
current += String(char)
}
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [Character]()
var current = ""
for char in parenString where char != " " {
if char == "(" {
if !stack.isEmpty {
current += String(char)
}
stack.append(char)
} else if char == ")" {
if stack.last == "(" {
stack.removeLast()
}
if stack.isEmpty {
result.append(current)
current = ""
} else {
current += String(char)
}
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var current: String = ""
var openCount: Int = 0
for char in parenString {
if char == "(" {
openCount += 1
current += String(char)
} else if char == ")" {
openCount -= 1
current += String(char)
} else if char == " " {
continue
} else {
current += String(char)
}
if openCount == 0 {
result.append(current)
current = ""
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var current: String = ""
var openCount: Int = 0
for char in parenString {
if char == "(" {
openCount += 1
current += String(char)
} else if char == ")" {
openCount -= 1
current += String(char)
} else if char == " " {
continue
} else {
current += String(char)
}
if openCount == 0 {
result.append(current)
current = ""
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup: String = ""
var level: Int = 0
for char in parenString {
if char == "(" {
level += 1
currentGroup.append(char)
} else if char == ")" {
level -= 1
currentGroup.append(char)
if level == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup: String = ""
var level: Int = 0
for char in parenString {
if char == "(" {
level += 1
currentGroup.append(char)
} else if char == ")" {
level -= 1
currentGroup.append(char)
if level == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var current: String = ""
var stack: [String] = []
for char in parenString {
if char == "(" {
stack.append("(")
current.append("(")
} else if char == ")" {
if stack.isEmpty {
result.append(current)
current = ""
} else {
stack.removeLast()
current.append(")")
}
}
}
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 current: String = ""
var stack: [String] = []
for char in parenString {
if char == "(" {
stack.append("(")
current.append("(")
} else if char == ")" {
if stack.isEmpty {
result.append(current)
current = ""
} else {
stack.removeLast()
current.append(")")
}
}
}
if !current.isEmpty {
result.append(current)
}
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 += String(char)
} else if char == ")" {
if stack.last == "(" {
stack.removeLast()
current += String(char)
if stack.isEmpty {
result.append(current)
current = ""
}
} else {
result.append(current)
current = ""
stack.append(")")
}
}
}
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 += String(char)
} else if char == ")" {
if stack.last == "(" {
stack.removeLast()
current += String(char)
if stack.isEmpty {
result.append(current)
current = ""
}
} else {
result.append(current)
current = ""
stack.append(")")
}
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var currentOpenParens = 0
for char in parenString {
if char == " " {
continue
}
if char == "(" {
currentOpenParens += 1
} else if char == ")" {
currentOpenParens -= 1
}
currentString.append(char)
if currentOpenParens == 0 {
result.append(currentString)
currentString = ""
}
}
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 currentString = ""
var currentOpenParens = 0
for char in parenString {
if char == " " {
continue
}
if char == "(" {
currentOpenParens += 1
} else if char == ")" {
currentOpenParens -= 1
}
currentString.append(char)
if currentOpenParens == 0 {
result.append(currentString)
currentString = ""
}
}
return result
}
```
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 - 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.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
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.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
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 {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func belowZero(operations: [Int]) -> Bool {
// TODO: Implement me
}
```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 {
// TODO: Implement me
}
```
} // missing return in global function expected to return 'Bool'
func belowZero(operations: [Int]) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func belowZero(operations: [Int]) -> Bool {
// your code here
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 {
// your code here
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
// Write your code here
var balance = 0
for i in 0..<operations.count {
if operations[i] > 0 {
balance += operations[i]
} else if operations[i] < 0 {
balance -= operations[i]
}
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 {
// Write your code here
var balance = 0
for i in 0..<operations.count {
if operations[i] > 0 {
balance += operations[i]
} else if operations[i] < 0 {
balance -= operations[i]
}
if balance < 0 {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func belowZero(operations: [Int]) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
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 {
// Write your code here
var balance = 0
for i in operations {
balance += i
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 {
// Write your code here
var balance = 0
for i in operations {
balance += i
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 = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
let sumOfDeviations = deviations.reduce(0, +)
return sumOfDeviations / 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 = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
let sumOfDeviations = deviations.reduce(0, +)
return sumOfDeviations / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
var sum = 0.0
var count = 0
for number in numbers {
sum += number
count += 1
}
let mean = sum / Double(count)
var sumOfDifferences = 0.0
for number in numbers {
let difference = abs(number - mean)
sumOfDifferences += difference
}
return sumOfDifferences / Double(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 {
var sum = 0.0
var count = 0
for number in numbers {
sum += number
count += 1
}
let mean = sum / Double(count)
var sumOfDifferences = 0.0
for number in numbers {
let difference = abs(number - mean)
sumOfDifferences += difference
}
return sumOfDifferences / Double(count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Double'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
// TODO: Implement me!
}
```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 {
// TODO: Implement me!
}
```
} // missing return in global function expected to return 'Double'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let absoluteDifferences = numbers.map { abs($0 - mean) }
return absoluteDifferences.reduce(0, +) / Double(absoluteDifferences.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let absoluteDifferences = numbers.map { abs($0 - mean) }
return absoluteDifferences.reduce(0, +) / Double(absoluteDifferences.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
guard numbers.count > 0 else {
return 0
}
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (result, number) -> Double in
return result + abs(number - mean)
} / 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 {
guard numbers.count > 0 else {
return 0
}
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (result, number) -> Double in
return result + abs(number - mean)
} / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
// TODO: Implement this function
return 0.0
}
```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 {
// TODO: Implement this function
return 0.0
}
```
// XCTAssertTrue failed
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
var sum = 0.0
for number in numbers {
sum += number
}
let mean = sum / Double(numbers.count)
var sumOfDifferences = 0.0
for number in numbers {
sumOfDifferences += abs(number - mean)
}
return sumOfDifferences / 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 {
var sum = 0.0
for number in numbers {
sum += number
}
let mean = sum / Double(numbers.count)
var sumOfDifferences = 0.0
for number in numbers {
sumOfDifferences += abs(number - mean)
}
return sumOfDifferences / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
// TODO: Implement this function
return 0
}
```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 {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
var sum = 0.0
var count = 0
var mean = 0.0
for number in numbers {
sum += number
count += 1
}
mean = sum / Double(count)
var sumOfAbsoluteDeviations = 0.0
for number in numbers {
sumOfAbsoluteDeviations += abs(number - mean)
}
return sumOfAbsoluteDeviations / Double(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 {
var sum = 0.0
var count = 0
var mean = 0.0
for number in numbers {
sum += number
count += 1
}
mean = sum / Double(count)
var sumOfAbsoluteDeviations = 0.0
for number in numbers {
sumOfAbsoluteDeviations += abs(number - mean)
}
return sumOfAbsoluteDeviations / Double(count)
}
```
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() {
if index == 0 {
result.append(number)
} else {
result.append(delimeter)
result.append(number)
}
}
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() {
if index == 0 {
result.append(number)
} else {
result.append(delimeter)
result.append(number)
}
}
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() {
if index < numbers.count - 1 {
result.append(number)
result.append(delimeter)
} else {
result.append(number)
}
}
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() {
if index < numbers.count - 1 {
result.append(number)
result.append(delimeter)
} else {
result.append(number)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, number) in numbers.enumerated() {
if index != numbers.count - 1 {
result.append(number)
result.append(delimeter)
} else {
result.append(number)
}
}
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() {
if index != numbers.count - 1 {
result.append(number)
result.append(delimeter)
} else {
result.append(number)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, value) in numbers.enumerated() {
result.append(value)
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, value) in numbers.enumerated() {
result.append(value)
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() {
if index == 0 {
result.append(number)
} else {
result.append(delimeter)
result.append(number)
}
}
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() {
if index == 0 {
result.append(number)
} else {
result.append(delimeter)
result.append(number)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, number) in numbers.enumerated() {
if index > 0 {
result.append(delimeter)
}
result.append(number)
}
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() {
if index > 0 {
result.append(delimeter)
}
result.append(number)
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, value) in numbers.enumerated() {
if index > 0 {
result.append(delimeter)
}
result.append(value)
}
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, value) in numbers.enumerated() {
if index > 0 {
result.append(delimeter)
}
result.append(value)
}
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] {
var parenLevels: [Int] = []
let parenStringArray = parenString.components(separatedBy: " ")
for paren in parenStringArray {
var parenLevel = 0
var parenLevelMax = 0
for char in paren {
if char == "(" {
parenLevel += 1
} else if char == ")" {
parenLevel -= 1
}
if parenLevel > parenLevelMax {
parenLevelMax = parenLevel
}
}
parenLevels.append(parenLevelMax)
}
return parenLevels
}
```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 parenLevels: [Int] = []
let parenStringArray = parenString.components(separatedBy: " ")
for paren in parenStringArray {
var parenLevel = 0
var parenLevelMax = 0
for char in paren {
if char == "(" {
parenLevel += 1
} else if char == ")" {
parenLevel -= 1
}
if parenLevel > parenLevelMax {
parenLevelMax = parenLevel
}
}
parenLevels.append(parenLevelMax)
}
return parenLevels
}
```
func parseNestedParens(parenString: String) -> [Int] {
var result: [Int] = []
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var parenStack: [Character] = []
var currentLevel = 0
for c in parenString {
switch c {
case "(":
parenStack.append(c)
currentLevel += 1
case ")":
parenStack.popLast()
currentLevel -= 1
default:
continue
}
result.append(currentLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result: [Int] = []
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var parenStack: [Character] = []
var currentLevel = 0
for c in parenString {
switch c {
case "(":
parenStack.append(c)
currentLevel += 1
case ")":
parenStack.popLast()
currentLevel -= 1
default:
continue
}
result.append(currentLevel)
}
return result
}
```
parenStack.popLast() // result of call to 'popLast()' is unused
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
return parenString.split(separator: " ").map { parseNestedParens(parenString: String($0)) }
}
func parseNestedParens(parenString: String) -> Int {
var maxLevel = 0
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
return maxLevel
}
```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] {
return parenString.split(separator: " ").map { parseNestedParens(parenString: String($0)) }
}
func parseNestedParens(parenString: String) -> Int {
var maxLevel = 0
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
return maxLevel
}
parseNestedParens(parenString: "(()()) ((())) () ((())()())")
```
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
let parenGroups = parenString.components(separatedBy: " ")
for group in parenGroups {
var level = 0
for char in group {
if char == "(" {
level += 1
} else if char == ")" {
level -= 1
}
}
result.append(level)
}
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]()
let parenGroups = parenString.components(separatedBy: " ")
for group in parenGroups {
var level = 0
for char in group {
if char == "(" {
level += 1
} else if char == ")" {
level -= 1
}
}
result.append(level)
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
return parenString.split(separator: " ").map {
var maxCount = 0
var count = 0
for char in $0 {
if char == "(" {
count += 1
} else {
count -= 1
}
maxCount = max(maxCount, count)
}
return maxCount
}
}
```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] {
return parenString.split(separator: " ").map {
var maxCount = 0
var count = 0
for char in $0 {
if char == "(" {
count += 1
} else {
count -= 1
}
maxCount = max(maxCount, count)
}
return maxCount
}
}
```
func parseNestedParens(parenString: String) -> [Int] {
var parenString = parenString
var result: [Int] = []
while let index = parenString.range(of: " ")?.lowerBound {
let paren = String(parenString[..<index])
result.append(parseNestedParens(parenString: paren))
parenString = String(parenString[parenString.index(after: index)...])
}
return result
}
func parseNestedParens(parenString: String) -> Int {
var max = 0
var count = 0
for c in parenString {
if c == "(" {
count += 1
max = max > count ? max : count
} else if c == ")" {
count -= 1
}
}
return max
}
```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 parenString = parenString
var result: [Int] = []
while let index = parenString.range(of: " ")?.lowerBound {
let paren = String(parenString[..<index])
result.append(parseNestedParens(parenString: paren))
parenString = String(parenString[parenString.index(after: index)...])
}
return result
}
func parseNestedParens(parenString: String) -> Int {
var max = 0
var count = 0
for c in parenString {
if c == "(" {
count += 1
max = max > count ? max : count
} else if c == ")" {
count -= 1
}
}
return max
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var parenString = parenString.replacingOccurrences(of: " ", with: "")
var maxParenDepth = 0
var parenDepth = 0
var parenDepthArray = [Int]()
for paren in parenString {
if paren == "(" {
parenDepth += 1
maxParenDepth = max(maxParenDepth, parenDepth)
} else {
parenDepth -= 1
}
if parenDepth == 0 {
parenDepthArray.append(maxParenDepth)
maxParenDepth = 0
}
}
return parenDepthArray
}
```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 parenString = parenString.replacingOccurrences(of: " ", with: "")
var maxParenDepth = 0
var parenDepth = 0
var parenDepthArray = [Int]()
for paren in parenString {
if paren == "(" {
parenDepth += 1
maxParenDepth = max(maxParenDepth, parenDepth)
} else {
parenDepth -= 1
}
if parenDepth == 0 {
parenDepthArray.append(maxParenDepth)
maxParenDepth = 0
}
}
return parenDepthArray
}
```
var parenString = parenString.replacingOccurrences(of: " ", with: "") // variable 'parenString' was never mutated; consider changing to 'let' constant
func parseNestedParens(parenString: String) -> [Int] {
return parenString.split(separator: " ").map {
var maxLevel = 0
var currentLevel = 0
for char in $0 {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
return maxLevel
}
}
```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] {
return parenString.split(separator: " ").map {
var maxLevel = 0
var currentLevel = 0
for char in $0 {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
return maxLevel
}
}
```
func parseNestedParens(parenString: String) -> [Int] {
return parenString.components(separatedBy: " ").map {
var maxLevel = 0
var level = 0
for char in $0 {
if char == "(" {
level += 1
if level > maxLevel {
maxLevel = level
}
} else {
level -= 1
}
}
return maxLevel
}
}
```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] {
return parenString.components(separatedBy: " ").map {
var maxLevel = 0
var level = 0
for char in $0 {
if char == "(" {
level += 1
if level > maxLevel {
maxLevel = level
}
} else {
level -= 1
}
}
return maxLevel
}
}
```
func parseNestedParens(parenString: String) -> [Int] {
var parenString = parenString
var result: [Int] = []
while parenString.count > 0 {
var parenString = parenString
var parenStringArray = parenString.components(separatedBy: " ")
var maxLevel = 0
var level = 0
for char in parenStringArray[0] {
if char == "(" {
level += 1
if level > maxLevel {
maxLevel = level
}
} else if char == ")" {
level -= 1
}
}
result.append(maxLevel)
parenString = parenString.replacingOccurrences(of: parenStringArray[0], with: "")
}
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 parenString = parenString
var result: [Int] = []
while parenString.count > 0 {
var parenString = parenString
var parenStringArray = parenString.components(separatedBy: " ")
var maxLevel = 0
var level = 0
for char in parenStringArray[0] {
if char == "(" {
level += 1
if level > maxLevel {
maxLevel = level
}
} else if char == ")" {
level -= 1
}
}
result.append(maxLevel)
parenString = parenString.replacingOccurrences(of: parenStringArray[0], with: "")
}
return result
}
```
var parenString = parenString // variable 'parenString' was never mutated; consider changing to 'let' constant
var parenStringArray = parenString.components(separatedBy: " ") // variable 'parenStringArray' was never mutated; consider changing to 'let' constant
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] {
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] {
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 sumProduct(numbers: [Int]) -> (Int, Int) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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) {
let sum = numbers.reduce(0, +)
let product = numbers.reduce(1, *)
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 rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else {
return []
}
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] {
guard numbers.count > 0 else {
return []
}
var result = [Int]()
var max = numbers[0]
for number in numbers {
result.append(max)
if number > max {
max = number
}
}
return result
}
```
// XCTAssertTrue failed
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else {
return []
}
var maxes = [Int]()
var currentMax = numbers[0]
maxes.append(currentMax)
for i in 1..<numbers.count {
let current = numbers[i]
if current > currentMax {
currentMax = current
}
maxes.append(currentMax)
}
return maxes
}
```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] {
guard numbers.count > 0 else {
return []
}
var maxes = [Int]()
var currentMax = numbers[0]
maxes.append(currentMax)
for i in 1..<numbers.count {
let current = numbers[i]
if current > currentMax {
currentMax = current
}
maxes.append(currentMax)
}
return maxes
}
```
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 1 else { return numbers }
var result = [Int]()
var max = numbers[0]
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 1 else { return numbers }
var result = [Int]()
var max = numbers[0]
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else {
return []
}
var maxes = [Int]()
var currentMax = numbers[0]
maxes.append(currentMax)
for number in numbers[1 ..< numbers.count] {
if number > currentMax {
currentMax = number
}
maxes.append(currentMax)
}
return maxes
}
```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] {
guard numbers.count > 0 else {
return []
}
var maxes = [Int]()
var currentMax = numbers[0]
maxes.append(currentMax)
for number in numbers[1 ..< numbers.count] {
if number > currentMax {
currentMax = number
}
maxes.append(currentMax)
}
return maxes
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```
func makePalindrome(string: String) -> String {
let length = string.count
guard length > 0 else { return string }
let stringArray = Array(string)
var i = length - 1
var j = length - 1
while i >= 0 && j >= 0 && stringArray[i] == stringArray[j] {
i -= 1
j -= 1
}
return String(stringArray[0..<i].reversed()) + string
}
```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 length = string.count
guard length > 0 else { return string }
let stringArray = Array(string)
var i = length - 1
var j = length - 1
while i >= 0 && j >= 0 && stringArray[i] == stringArray[j] {
i -= 1
j -= 1
}
return String(stringArray[0..<i].reversed()) + string
}
```
// Fatal error: Range requires lowerBound <= upperBound
func makePalindrome(string: String) -> String {
let string = string.characters
let count = string.count
var start = 0
var end = count - 1
var isPalindrome = false
while !isPalindrome && start < end {
if string[start] == string[end] {
start += 1
end -= 1
} else {
start = 0
end = count - 1 - start
}
if start == end || start == end - 1 {
isPalindrome = true
}
}
let prefix = string[0..<start]
let suffix = string[end..<count]
let reversePrefix = String(prefix.characters.reversed())
return reversePrefix + String(string.characters) + String(suffix.characters.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 string = string.characters
let count = string.count
var start = 0
var end = count - 1
var isPalindrome = false
while !isPalindrome && start < end {
if string[start] == string[end] {
start += 1
end -= 1
} else {
start = 0
end = count - 1 - start
}
if start == end || start == end - 1 {
isPalindrome = true
}
}
let prefix = string[0..<start]
let suffix = string[end..<count]
let reversePrefix = String(prefix.characters.reversed())
return reversePrefix + String(string.characters) + String(suffix.characters.reversed())
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
if string[start] == string[end] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[start] == string[end] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
let prefix = string[0..<start] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let suffix = string[end..<count] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let reversePrefix = String(prefix.characters.reversed()) // 'characters' is unavailable: Please use String directly
return reversePrefix + String(string.characters) + String(suffix.characters.reversed()) // 'characters' is unavailable: Please use String directly
return reversePrefix + String(string.characters) + String(suffix.characters.reversed()) // 'characters' is unavailable: Please use String directly
func makePalindrome(string: String) -> String {
let string = string.reversed()
var start = 0
var end = string.count - 1
while start < end && string[start] == string[end] {
start += 1
end -= 1
}
let prefix = String(string[..<string.index(string.startIndex, offsetBy: start)])
let suffix = String(string[string.index(string.startIndex, offsetBy: start)...])
let reversedSuffix = String(suffix.reversed())
return reversedSuffix + prefix
}
```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 string = string.reversed()
var start = 0
var end = string.count - 1
while start < end && string[start] == string[end] {
start += 1
end -= 1
}
let prefix = String(string[..<string.index(string.startIndex, offsetBy: start)])
let suffix = String(string[string.index(string.startIndex, offsetBy: start)...])
let reversedSuffix = String(suffix.reversed())
return reversedSuffix + prefix
}
```
while start < end && string[start] == string[end] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<String>.Index'
while start < end && string[start] == string[end] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<String>.Index'
```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 string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
let string = string.joined(separator: "")
let string = string.characters.reversed()
let string = string.map { String($0) }
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 string = string.reversed()
var length = 0
while length < string.count && string.prefix(length) == string.suffix(length) {
length += 1
}
return string.prefix(length) + string.prefix(string.count - length).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 string = string.reversed()
var length = 0
while length < string.count && string.prefix(length) == string.suffix(length) {
length += 1
}
return string.prefix(length) + string.prefix(string.count - length).reversed()
}
```
while length < string.count && string.prefix(length) == string.suffix(length) { // cannot convert value of type 'ReversedCollection<String>.SubSequence' (aka 'Slice<ReversedCollection<String>>') to expected argument type '[ReversedCollection<String>.Element]' (aka 'Array<Character>')
return string.prefix(length) + string.prefix(string.count - length).reversed() // cannot convert return expression of type '[Slice<ReversedCollection<String>>.Element]' (aka 'Array<Character>') to return type 'String'
func makePalindrome(string: String) -> String {
let string = string.reversed()
var start = 0
var end = string.count - 1
while start < end && string[start] == string[end] {
start += 1
end -= 1
}
let prefix = String(string[start...end].reversed())
return string + prefix
}
```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 string = string.reversed()
var start = 0
var end = string.count - 1
while start < end && string[start] == string[end] {
start += 1
end -= 1
}
let prefix = String(string[start...end].reversed())
return string + prefix
}
```
while start < end && string[start] == string[end] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<String>.Index'
while start < end && string[start] == string[end] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<String>.Index'
let prefix = String(string[start...end].reversed()) // subscript 'subscript(_:)' requires the types 'ReversedCollection<String>.Index' and 'Int' be equivalent
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let length = string.characters.count
var palindrome = string
var i = length - 1
while i > 0 {
let sub = string[Range(string.startIndex..<string.index(string.startIndex, offsetBy: i))]
if sub == sub.reversed() {
palindrome = string + String(sub.reversed())
break
}
i -= 1
}
return palindrome
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let length = string.characters.count
var palindrome = string
var i = length - 1
while i > 0 {
let sub = string[Range(string.startIndex..<string.index(string.startIndex, offsetBy: i))]
if sub == sub.reversed() {
palindrome = string + String(sub.reversed())
break
}
i -= 1
}
return palindrome
}
```
let length = string.characters.count // 'characters' is unavailable: Please use String directly
let sub = string[Range(string.startIndex..<string.index(string.startIndex, offsetBy: i))] // referencing initializer 'init(_:)' on 'Range' requires that 'String.Index' conform to 'Strideable'
func makePalindrome(string: String) -> String {
let string = string.reversed()
var i = 0
var j = string.count - 1
while i < j {
if string[i] == string[j] {
i += 1
j -= 1
} else {
break
}
}
return String(string[i...j]) + string
}
```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 string = string.reversed()
var i = 0
var j = string.count - 1
while i < j {
if string[i] == string[j] {
i += 1
j -= 1
} else {
break
}
}
return String(string[i...j]) + string
}
```
if string[i] == string[j] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<String>.Index'
if string[i] == string[j] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<String>.Index'
return String(string[i...j]) + string // subscript 'subscript(_:)' requires the types 'ReversedCollection<String>.Index' and 'Int' be equivalent
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let stringCount = string.count
var isPalindrome = false
var palindromeStartIndex = stringCount
var palindromeEndIndex = stringCount
for i in 0..<stringCount {
for j in (i..<stringCount).reversed() {
let substring = String(string[i...j])
let substringCount = substring.count
if substring == String(substring.reversed()) {
isPalindrome = true
if substringCount > palindromeEndIndex - palindromeStartIndex {
palindromeStartIndex = i
palindromeEndIndex = j
}
}
}
if isPalindrome {
break
}
}
let prefix = String(string[0..<palindromeStartIndex])
let suffix = String(string[palindromeEndIndex..<stringCount])
let reversedPrefix = String(prefix.reversed())
return reversedPrefix + string + suffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let stringCount = string.count
var isPalindrome = false
var palindromeStartIndex = stringCount
var palindromeEndIndex = stringCount
for i in 0..<stringCount {
for j in (i..<stringCount).reversed() {
let substring = String(string[i...j])
let substringCount = substring.count
if substring == String(substring.reversed()) {
isPalindrome = true
if substringCount > palindromeEndIndex - palindromeStartIndex {
palindromeStartIndex = i
palindromeEndIndex = j
}
}
}
if isPalindrome {
break
}
}
let prefix = String(string[0..<palindromeStartIndex])
let suffix = String(string[palindromeEndIndex..<stringCount])
let reversedPrefix = String(prefix.reversed())
return reversedPrefix + string + suffix
}
```
let substring = String(string[i...j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let prefix = String(string[0..<palindromeStartIndex]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let suffix = String(string[palindromeEndIndex..<stringCount]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func makePalindrome(string: String) -> String {
let string = string.reversed()
let string = string.characters.map { String($0) }
var suffix = ""
var prefix = ""
var index = string.count - 1
var lastIndex = string.count - 1
while index >= 0 {
if string[index] == string[lastIndex] {
suffix += string[index]
lastIndex = index
}
index -= 1
}
prefix = string.suffix(from: lastIndex).reversed().joined(separator: "")
return prefix + suffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.reversed()
let string = string.characters.map { String($0) }
var suffix = ""
var prefix = ""
var index = string.count - 1
var lastIndex = string.count - 1
while index >= 0 {
if string[index] == string[lastIndex] {
suffix += string[index]
lastIndex = index
}
index -= 1
}
prefix = string.suffix(from: lastIndex).reversed().joined(separator: "")
return prefix + suffix
}
```
let string = string.characters.map { String($0) } // value of type 'ReversedCollection<String>' has no member 'characters'
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
let c = zip(a, b).map { $0 ^ $1 }
return String(c)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
let c = zip(a, b).map { $0 ^ $1 }
return String(c)
}
```
let c = zip(a, b).map { $0 ^ $1 } // binary operator '^' cannot be applied to two 'String.Element' (aka 'Character') operands
func stringXor(a: String, b: String) -> String {
let aArray = Array(a)
let bArray = Array(b)
var result: [Character] = []
for i in 0..<aArray.count {
let aChar = aArray[i]
let bChar = bArray[i]
if aChar != bChar {
result.append("1")
} else {
result.append("0")
}
}
return String(result)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let aArray = Array(a)
let bArray = Array(b)
var result: [Character] = []
for i in 0..<aArray.count {
let aChar = aArray[i]
let bChar = bArray[i]
if aChar != bChar {
result.append("1")
} else {
result.append("0")
}
}
return String(result)
}
```
func stringXor(a: String, b: String) -> String {
return String(zip(a, b).map { $0 != $1 ? "1" : "0" }.joined())
}
```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 {
return String(zip(a, b).map { $0 != $1 ? "1" : "0" }.joined())
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
let aChars = Array(a)
let bChars = Array(b)
for i in 0..<a.count {
if aChars[i] == bChars[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 = ""
let aChars = Array(a)
let bChars = Array(b)
for i in 0..<a.count {
if aChars[i] == bChars[i] {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
let aArray = Array(a)
let bArray = Array(b)
for (index, char) in aArray.enumerated() {
if char == bArray[index] {
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 = ""
let aArray = Array(a)
let bArray = Array(b)
for (index, char) in aArray.enumerated() {
if char == bArray[index] {
result += "0"
} else {
result += "1"
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
let aArray = a.map { String($0) }
let bArray = b.map { String($0) }
for i in 0 ..< aArray.count {
if aArray[i] == bArray[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 = ""
let aArray = a.map { String($0) }
let bArray = b.map { String($0) }
for i in 0 ..< aArray.count {
if aArray[i] == bArray[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
let aArray = a.map { $0 }
let bArray = b.map { $0 }
var xorArray: [Character] = []
for (index, _) in aArray.enumerated() {
xorArray.append(aArray[index] == bArray[index] ? "0" : "1")
}
return String(xorArray)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let aArray = a.map { $0 }
let bArray = b.map { $0 }
var xorArray: [Character] = []
for (index, _) in aArray.enumerated() {
xorArray.append(aArray[index] == bArray[index] ? "0" : "1")
}
return String(xorArray)
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for (index, char) in a.enumerated() {
let charB = b[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[b.index(b.startIndex, offsetBy: index)]
if char == charB {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'String'
func stringXor(a: String, b: String) -> String {
var result = ""
for (index, char) in a.enumerated() {
result += String(Int(String(char))! ^ Int(String(b[b.index(b.startIndex, offsetBy: index)]))!)
}
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() {
result += String(Int(String(char))! ^ Int(String(b[b.index(b.startIndex, offsetBy: index)]))!)
}
return result
}
```
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
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? {
guard !strings.isEmpty else {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
func longest(strings: [String]) -> String? {
var longestString = ""
for string in strings {
if string.count > longestString.count {
longestString = string
}
}
return longestString
}
```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 longestString = ""
for string in strings {
if string.count > longestString.count {
longestString = string
}
}
return longestString
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
if strings.count == 0 {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.count == 0 {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
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? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```
func longest(strings: [String]) -> String? {
// TODO: Implement this function
}
```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? {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'String?'
func longest(strings: [String]) -> String? {
return strings.max { $0.count < $1.count }
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
return strings.max { $0.count < $1.count }
}
```
func longest(strings: [String]) -> String? {
return strings.sorted { $0.count > $1.count }.first
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
return strings.sorted { $0.count > $1.count }.first
}
```
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else {
return nil
}
var max = strings[0]
for string in strings {
if string.count > max.count {
max = string
}
}
return max
}
```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? {
guard !strings.isEmpty else {
return nil
}
var max = strings[0]
for string in strings {
if string.count > max.count {
max = string
}
}
return max
}
```
func longest(strings: [String]) -> String? {
guard strings.count > 0 else {
return nil
}
var longestString = strings[0]
for string in strings {
if string.count > longestString.count {
longestString = string
}
}
return longestString
}
```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? {
guard strings.count > 0 else {
return nil
}
var longestString = strings[0]
for string in strings {
if string.count > longestString.count {
longestString = string
}
}
return longestString
}
```
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longestString = strings[0]
for string in strings {
if string.count > longestString.count {
longestString = string
}
}
return longestString
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longestString = strings[0]
for string in strings {
if string.count > longestString.count {
longestString = string
}
}
return longestString
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement this function
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement this function
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement me!
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement me!
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement this function
return 0
}
```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 {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement this function
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement this function
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Implement this function
return 0
}
```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 {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 || b == 0 {
return a + b
}
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 a == 0 || b == 0 {
return a + b
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func allPrefixes(string: String) -> [String] {
var prefixArray: [String] = []
for i in 1...string.count {
prefixArray.append(String(string.prefix(i)))
}
return prefixArray
}
```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 prefixArray: [String] = []
for i in 1...string.count {
prefixArray.append(String(string.prefix(i)))
}
return prefixArray
}
```
// Fatal error: Range requires lowerBound <= upperBound
func allPrefixes(string: String) -> [String] {
let prefixLength = string.count
var prefixes = [String]()
for i in 0..<prefixLength {
prefixes.append(String(string[..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
let prefixLength = string.count
var prefixes = [String]()
for i in 0..<prefixLength {
prefixes.append(String(string[..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
print(allPrefixes(string: "abc"))
```
func allPrefixes(string: String) -> [String] {
let prefix = string.prefix(1)
let prefixString = String(prefix)
if prefixString.count == string.count {
return [prefixString]
} else {
let prefixes = allPrefixes(string: string.dropFirst(1))
return [prefixString] + prefixes
}
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
let prefix = string.prefix(1)
let prefixString = String(prefix)
if prefixString.count == string.count {
return [prefixString]
} else {
let prefixes = allPrefixes(string: string.dropFirst(1))
return [prefixString] + prefixes
}
}
```
let prefixes = allPrefixes(string: string.dropFirst(1)) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func allPrefixes(string: String) -> [String] {
return string.indices.map { string.prefix(upTo: $0) }
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
return string.indices.map { string.prefix(upTo: $0) }
}
```
return string.indices.map { string.prefix(upTo: $0) } // cannot convert value of type 'String.SubSequence' (aka 'Substring') to closure result type 'String'
func allPrefixes(string: String) -> [String] {
let prefixArray = string.characters.map { String($0) }
var allPrefixes = [String]()
for index in 0..<prefixArray.count {
allPrefixes.append(prefixArray[0...index].joinWithSeparator(""))
}
return allPrefixes
}
```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] {
let prefixArray = string.characters.map { String($0) }
var allPrefixes = [String]()
for index in 0..<prefixArray.count {
allPrefixes.append(prefixArray[0...index].joinWithSeparator(""))
}
return allPrefixes
}
```
let prefixArray = string.characters.map { String($0) } // 'characters' is unavailable: Please use String directly
allPrefixes.append(prefixArray[0...index].joinWithSeparator("")) // value of type 'Array<String>.SubSequence' (aka 'ArraySlice<String>') has no member 'joinWithSeparator'
func allPrefixes(string: String) -> [String] {
// TODO: Implement this function
var prefixArray = [String]()
for i in 1...string.count {
prefixArray.append(String(string.prefix(i)))
}
return prefixArray
}
```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] {
// TODO: Implement this function
var prefixArray = [String]()
for i in 1...string.count {
prefixArray.append(String(string.prefix(i)))
}
return prefixArray
}
```
// Fatal error: Range requires lowerBound <= upperBound
func allPrefixes(string: String) -> [String] {
let prefixCount = string.count
var prefixArray = [String]()
for i in 0 ... prefixCount {
prefixArray.append(String(string.prefix(i)))
}
return prefixArray
}
```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] {
let prefixCount = string.count
var prefixArray = [String]()
for i in 0 ... prefixCount {
prefixArray.append(String(string.prefix(i)))
}
return prefixArray
}
```
// XCTAssertTrue failed
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for index in 0..<string.count {
prefixes.append(String(string[..<string.index(string.startIndex, offsetBy: index + 1)]))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for index in 0..<string.count {
prefixes.append(String(string[..<string.index(string.startIndex, offsetBy: index + 1)]))
}
return prefixes
}
```
func allPrefixes(string: String) -> [String] {
return string.indices.map { string.prefix($0 + 1) }
}
```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] {
return string.indices.map { string.prefix($0 + 1) }
}
```
return string.indices.map { string.prefix($0 + 1) } // cannot convert value of type 'DefaultIndices<String>.Element' (aka 'String.Index') to expected argument type 'Int'
func allPrefixes(string: String) -> [String] {
// Your code here
var prefixes = [String]()
var prefix = ""
for char in string {
prefix += String(char)
prefixes.append(prefix)
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
// Your code here
var prefixes = [String]()
var prefix = ""
for char in string {
prefix += String(char)
prefixes.append(prefix)
}
return prefixes
}
```
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 {
if i == n {
result += "\(i)"
} else {
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 {
if i == n {
result += "\(i)"
} else {
result += "\(i) "
}
}
return result
}
```
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 {
let numbers = (0 ... n).map { String($0) }
return numbers.joined(separator: " ")
}
```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 {
let numbers = (0 ... n).map { String($0) }
return numbers.joined(separator: " ")
}
```
func stringSequence(n: Int) -> String {
let numbers = Array(0...n)
let stringNumbers = numbers.map { String($0) }
return stringNumbers.joined(separator: " ")
}
```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 {
let numbers = Array(0...n)
let stringNumbers = numbers.map { String($0) }
return stringNumbers.joined(separator: " ")
}
```
func stringSequence(n: Int) -> String {
return String(0..<n+1).joined(separator: " ")
}
```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 {
return String(0..<n+1).joined(separator: " ")
}
```
return String(0..<n+1).joined(separator: " ") // no exact matches in call to initializer
return String(0..<n+1).joined(separator: " ") // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trimmingCharacters(in: .whitespaces)
}
```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.trimmingCharacters(in: .whitespaces)
}
```
func stringSequence(n: Int) -> String {
// Write your code here.
return ""
}
```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 {
// Write your code here.
return ""
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return String(0..<n+1).replacingOccurrences(of: " ", with: " ")
}
```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 {
return String(0..<n+1).replacingOccurrences(of: " ", with: " ")
}
```
return String(0..<n+1).replacingOccurrences(of: " ", with: " ") // no exact matches in call to initializer
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trimmingCharacters(in: .whitespaces)
}
```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.trimmingCharacters(in: .whitespaces)
}
```
func countDistinctCharacters(string: String) -> Int {
return string.lowercased().characters.reduce([Character: Int]()) { (charMap, char) in
var charMap = charMap
if charMap[char] == nil {
charMap[char] = 1
} else {
charMap[char]! += 1
}
return charMap
}.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 string.lowercased().characters.reduce([Character: Int]()) { (charMap, char) in
var charMap = charMap
if charMap[char] == nil {
charMap[char] = 1
} else {
charMap[char]! += 1
}
return charMap
}.count
}
```
return string.lowercased().characters.reduce([Character: Int]()) { (charMap, char) in // 'characters' is unavailable: Please use String directly
func countDistinctCharacters(string: String) -> Int {
return string.lowercased().reduce(into: Set<Character>()) {
$0.insert($1)
}.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 string.lowercased().reduce(into: Set<Character>()) {
$0.insert($1)
}.count
}
```
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string.lowercased() {
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.lowercased() {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string.lowercased() {
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.lowercased() {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
let lowerCasedString = string.lowercased()
var distinctCharacters = Set<Character>()
for character in lowerCasedString {
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 {
let lowerCasedString = string.lowercased()
var distinctCharacters = Set<Character>()
for character in lowerCasedString {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
return string.lowercased().reduce(into: Set<Character>()) {
$0.insert($1)
}.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 string.lowercased().reduce(into: Set<Character>()) {
$0.insert($1)
}.count
}
```
func countDistinctCharacters(string: String) -> Int {
let lowerCasedString = string.lowercased()
var distinctCharacters = Set<Character>()
for character in lowerCasedString {
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 {
let lowerCasedString = string.lowercased()
var distinctCharacters = Set<Character>()
for character in lowerCasedString {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
let lowerCased = string.lowercased()
let set = Set(lowerCased)
return set.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let lowerCased = string.lowercased()
let set = Set(lowerCased)
return set.count
}
```
func countDistinctCharacters(string: String) -> Int {
// TODO: Implement this function
return 0
}
```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: Implement this function
return 0
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
return string.lowercased().removeDuplicates().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 string.lowercased().removeDuplicates().count
}
```
return string.lowercased().removeDuplicates().count // value of type 'String' has no member 'removeDuplicates'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var temp = ""
for char in musicString {
if char == " " {
if temp == "o" {
result.append(4)
} else if temp == "o|" {
result.append(2)
} else if temp == ".|" {
result.append(1)
}
temp = ""
} else {
temp.append(char)
}
}
if temp == "o" {
result.append(4)
} else if temp == "o|" {
result.append(2)
} else if temp == ".|" {
result.append(1)
}
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 temp = ""
for char in musicString {
if char == " " {
if temp == "o" {
result.append(4)
} else if temp == "o|" {
result.append(2)
} else if temp == ".|" {
result.append(1)
}
temp = ""
} else {
temp.append(char)
}
}
if temp == "o" {
result.append(4)
} else if temp == "o|" {
result.append(2)
} else if temp == ".|" {
result.append(1)
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
let notes = musicString.split(separator: " ")
for note in notes {
if note.contains("o") {
result.append(4)
} else if note.contains("o|") {
result.append(2)
} else if note.contains(".") {
result.append(1)
}
}
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 {
if note.contains("o") {
result.append(4)
} else if note.contains("o|") {
result.append(2)
} else if note.contains(".") {
result.append(1)
}
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
let notes = musicString.split(separator: " ")
for note in notes {
if note.last == "o" {
result.append(4)
} else if note.last == "|" {
result.append(2)
} else if note.last == "." {
result.append(1)
}
}
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 {
if note.last == "o" {
result.append(4)
} else if note.last == "|" {
result.append(2)
} else if note.last == "." {
result.append(1)
}
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var temp: String = ""
for char in musicString {
if char == " " {
if temp == "o" {
result.append(4)
} else if temp == "o|" {
result.append(2)
} else if temp == ".|" {
result.append(1)
}
temp = ""
} else {
temp.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 temp: String = ""
for char in musicString {
if char == " " {
if temp == "o" {
result.append(4)
} else if temp == "o|" {
result.append(2)
} else if temp == ".|" {
result.append(1)
}
temp = ""
} else {
temp.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var musicArray = [Int]()
let musicStringArray = musicString.components(separatedBy: " ")
for music in musicStringArray {
switch music {
case "o":
musicArray.append(4)
case "o|":
musicArray.append(2)
case ".|":
musicArray.append(1)
default:
break
}
}
return musicArray
}
```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 musicArray = [Int]()
let musicStringArray = musicString.components(separatedBy: " ")
for music in musicStringArray {
switch music {
case "o":
musicArray.append(4)
case "o|":
musicArray.append(2)
case ".|":
musicArray.append(1)
default:
break
}
}
return musicArray
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.components(separatedBy: " ")
for note in notes {
let beats = note.components(separatedBy: ".|").count
result.append(beats)
}
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.components(separatedBy: " ")
for note in notes {
let beats = note.components(separatedBy: ".|").count
result.append(beats)
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var beats = [Int]()
let notes = musicString.components(separatedBy: " ")
for note in notes {
let noteLength = note.count
if noteLength == 1 {
beats.append(4)
} else if noteLength == 2 {
beats.append(2)
} else {
beats.append(1)
}
}
return beats
}
```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 beats = [Int]()
let notes = musicString.components(separatedBy: " ")
for note in notes {
let noteLength = note.count
if noteLength == 1 {
beats.append(4)
} else if noteLength == 2 {
beats.append(2)
} else {
beats.append(1)
}
}
return beats
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
let notes = musicString.components(separatedBy: " ")
for note in notes {
if note == "o" {
result.append(4)
} else if note == "o|" {
result.append(2)
} else if note == ".|" {
result.append(1)
}
}
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.components(separatedBy: " ")
for note in notes {
if note == "o" {
result.append(4)
} else if note == "o|" {
result.append(2)
} else if note == ".|" {
result.append(1)
}
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
let notes = musicString.split(separator: " ")
for note in notes {
if note.count == 1 {
result.append(4)
} else if note.count == 2 {
result.append(2)
} else {
result.append(1)
}
}
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 {
if note.count == 1 {
result.append(4)
} else if note.count == 2 {
result.append(2)
} else {
result.append(1)
}
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var musicString = musicString
while musicString.count > 0 {
let firstCharacter = musicString.first!
if firstCharacter == "o" {
result.append(4)
musicString.removeFirst()
} else if firstCharacter == "|" {
musicString.removeFirst()
let nextCharacter = musicString.first!
if nextCharacter == "o" {
result.append(2)
musicString.removeFirst()
} else if nextCharacter == "." {
result.append(1)
musicString.removeFirst()
}
} else if firstCharacter == "." {
result.append(1)
musicString.removeFirst()
}
}
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 musicString = musicString
while musicString.count > 0 {
let firstCharacter = musicString.first!
if firstCharacter == "o" {
result.append(4)
musicString.removeFirst()
} else if firstCharacter == "|" {
musicString.removeFirst()
let nextCharacter = musicString.first!
if nextCharacter == "o" {
result.append(2)
musicString.removeFirst()
} else if nextCharacter == "." {
result.append(1)
musicString.removeFirst()
}
} else if firstCharacter == "." {
result.append(1)
musicString.removeFirst()
}
}
return result
}
```
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
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 let range = string.range(of: substring, options: .caseInsensitive, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index <= string.count - substring.count {
if string[string.index(string.startIndex, offsetBy: index)] == substring[substring.startIndex] {
count += 1
index += 1
} else {
index += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index <= string.count - substring.count {
if string[string.index(string.startIndex, offsetBy: index)] == substring[substring.startIndex] {
count += 1
index += 1
} else {
index += 1
}
}
return count
}
```
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if let range = string.range(of: substring, options: .literal, range: string.index(string.startIndex, offsetBy: index)...string.endIndex, locale: nil) {
count += 1
index = string.distance(from: string.startIndex, to: range.upperBound)
} else {
index = string.count
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if let range = string.range(of: substring, options: .literal, range: string.index(string.startIndex, offsetBy: index)...string.endIndex, locale: nil) {
count += 1
index = string.distance(from: string.startIndex, to: range.upperBound)
} else {
index = string.count
}
}
return count
}
```
if let range = string.range(of: substring, options: .literal, range: string.index(string.startIndex, offsetBy: index)...string.endIndex, locale: nil) { // cannot convert value of type 'ClosedRange<String.Index>' to expected argument type 'Range<String.Index>?'
func howManyTimes(string: String, substring: String) -> Int {
let stringArray = Array(string)
let substringArray = Array(substring)
var count = 0
var stringIndex = 0
var substringIndex = 0
while stringIndex < stringArray.count {
if stringArray[stringIndex] == substringArray[substringIndex] {
substringIndex += 1
if substringIndex == substringArray.count {
count += 1
substringIndex = 0
}
} else {
substringIndex = 0
}
stringIndex += 1
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let stringArray = Array(string)
let substringArray = Array(substring)
var count = 0
var stringIndex = 0
var substringIndex = 0
while stringIndex < stringArray.count {
if stringArray[stringIndex] == substringArray[substringIndex] {
substringIndex += 1
if substringIndex == substringArray.count {
count += 1
substringIndex = 0
}
} else {
substringIndex = 0
}
stringIndex += 1
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if string.hasPrefix(substring, range: string.range(from: index)) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if string.hasPrefix(substring, range: string.range(from: index)) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
```
if string.hasPrefix(substring, range: string.range(from: index)) { // extra argument 'from' in call
if string.hasPrefix(substring, range: string.range(from: index)) { // extra argument 'range' in call
if string.hasPrefix(substring, range: string.range(from: index)) { // missing argument for parameter 'of' in call
func howManyTimes(string: String, substring: String) -> Int {
let stringCount = string.count
let subCount = substring.count
var count = 0
for i in 0 ..< stringCount {
if string[i ... i + subCount - 1] == substring {
count += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let stringCount = string.count
let subCount = substring.count
var count = 0
for i in 0 ..< stringCount {
if string[i ... i + subCount - 1] == substring {
count += 1
}
}
return count
}
```
if string[i ... i + subCount - 1] == substring { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
let stringArray = Array(string)
let substringArray = Array(substring)
let substringLength = substringArray.count
var substringCount = 0
for index in 0..<stringArray.count {
if stringArray[index] == substringArray[0] {
if substringArray == Array(stringArray[index..<index+substringLength]) {
substringCount += 1
}
}
}
return substringCount
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let stringArray = Array(string)
let substringArray = Array(substring)
let substringLength = substringArray.count
var substringCount = 0
for index in 0..<stringArray.count {
if stringArray[index] == substringArray[0] {
if substringArray == Array(stringArray[index..<index+substringLength]) {
substringCount += 1
}
}
}
return substringCount
}
```
// Fatal error: Array index is out of range
func howManyTimes(string: String, substring: String) -> Int {
let stringCount = string.count
let substringCount = substring.count
if substringCount == 0 || substringCount > stringCount { return 0 }
var count = 0
for i in 0..<stringCount {
if string[i] == substring[0] {
var j = 1
while j < substringCount {
if i + j >= stringCount { break }
if string[i + j] != substring[j] { break }
j += 1
}
if j == substringCount {
count += 1
}
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let stringCount = string.count
let substringCount = substring.count
if substringCount == 0 || substringCount > stringCount { return 0 }
var count = 0
for i in 0..<stringCount {
if string[i] == substring[0] {
var j = 1
while j < substringCount {
if i + j >= stringCount { break }
if string[i + j] != substring[j] { break }
j += 1
}
if j == substringCount {
count += 1
}
}
}
return count
}
```
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i + j] != substring[j] { break } // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i + j] != substring[j] { break } // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func howManyTimes(string: String, substring: String) -> Int {
let string = string.lowercased()
let substring = substring.lowercased()
if string.isEmpty || substring.isEmpty {
return 0
}
var count = 0
var startIndex = 0
while true {
let index = string.index(string.startIndex, offsetBy: startIndex)
if let range = string.range(of: substring, range: index ..< string.endIndex) {
count += 1
startIndex = range.lowerBound.encodedOffset
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let string = string.lowercased()
let substring = substring.lowercased()
if string.isEmpty || substring.isEmpty {
return 0
}
var count = 0
var startIndex = 0
while true {
let index = string.index(string.startIndex, offsetBy: startIndex)
if let range = string.range(of: substring, range: index ..< string.endIndex) {
count += 1
startIndex = range.lowerBound.encodedOffset
} else {
break
}
}
return count
}
```
startIndex = range.lowerBound.encodedOffset // 'encodedOffset' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if string.range(of: substring, range: index..<string.endIndex) != nil {
count += 1
index = string.index(string.startIndex, offsetBy: substring.count, limitedBy: string.endIndex) ?? string.endIndex
} else {
index = string.index(index, offsetBy: 1, limitedBy: string.endIndex) ?? string.endIndex
}
}
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.range(of: substring, range: index..<string.endIndex) != nil {
count += 1
index = string.index(string.startIndex, offsetBy: substring.count, limitedBy: string.endIndex) ?? string.endIndex
} else {
index = string.index(index, offsetBy: 1, limitedBy: string.endIndex) ?? string.endIndex
}
}
return count
}
```
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let sortedNumbers = numbersArray.sorted { (num1, num2) -> Bool in
return num1 < num2
}
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 numbersArray = numbers.components(separatedBy: " ")
let sortedNumbers = numbersArray.sorted { (num1, num2) -> Bool in
return num1 < num2
}
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.split(separator: " ")
let sortedNumbers = numbersArray.sorted { $0 < $1 }
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 numbersArray = numbers.split(separator: " ")
let sortedNumbers = numbersArray.sorted { $0 < $1 }
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.split(separator: " ").map { String($0) }
let sortedNumbersArray = numbersArray.sorted {
let number1 = Int($0)!
let number2 = Int($1)!
return number1 < number2
}
return sortedNumbersArray.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 numbersArray = numbers.split(separator: " ").map { String($0) }
let sortedNumbersArray = numbersArray.sorted {
let number1 = Int($0)!
let number2 = Int($1)!
return number1 < number2
}
return sortedNumbersArray.joined(separator: " ")
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let sortedArray = numbersArray.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 numbersArray = numbers.components(separatedBy: " ")
let sortedArray = numbersArray.sorted()
return sortedArray.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.split(separator: " ")
var sortedNumbers: [String] = []
for number in numbersArray {
let numberString = String(number)
switch numberString {
case "zero":
sortedNumbers.append("zero")
case "one":
sortedNumbers.append("one")
case "two":
sortedNumbers.append("two")
case "three":
sortedNumbers.append("three")
case "four":
sortedNumbers.append("four")
case "five":
sortedNumbers.append("five")
case "six":
sortedNumbers.append("six")
case "seven":
sortedNumbers.append("seven")
case "eight":
sortedNumbers.append("eight")
case "nine":
sortedNumbers.append("nine")
default:
break
}
}
sortedNumbers.sort()
var sortedNumbersString = ""
for number in sortedNumbers {
sortedNumbersString.append("\(number) ")
}
return String(sortedNumbersString.dropLast())
}
```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 numbersArray = numbers.split(separator: " ")
var sortedNumbers: [String] = []
for number in numbersArray {
let numberString = String(number)
switch numberString {
case "zero":
sortedNumbers.append("zero")
case "one":
sortedNumbers.append("one")
case "two":
sortedNumbers.append("two")
case "three":
sortedNumbers.append("three")
case "four":
sortedNumbers.append("four")
case "five":
sortedNumbers.append("five")
case "six":
sortedNumbers.append("six")
case "seven":
sortedNumbers.append("seven")
case "eight":
sortedNumbers.append("eight")
case "nine":
sortedNumbers.append("nine")
default:
break
}
}
sortedNumbers.sort()
var sortedNumbersString = ""
for number in sortedNumbers {
sortedNumbersString.append("\(number) ")
}
return String(sortedNumbersString.dropLast())
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let sortedNumbers = numbersArray.sorted {
let firstNumber = $0
let secondNumber = $1
switch firstNumber {
case "zero": return true
case "one": return true
case "two": return true
case "three": return true
case "four": return true
case "five": return true
case "six": return true
case "seven": return true
case "eight": return true
case "nine": return true
default: return false
}
switch secondNumber {
case "zero": return false
case "one": return false
case "two": return false
case "three": return false
case "four": return false
case "five": return false
case "six": return false
case "seven": return false
case "eight": return false
case "nine": return false
default: return false
}
}
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 numbersArray = numbers.components(separatedBy: " ")
let sortedNumbers = numbersArray.sorted {
let firstNumber = $0
let secondNumber = $1
switch firstNumber {
case "zero": return true
case "one": return true
case "two": return true
case "three": return true
case "four": return true
case "five": return true
case "six": return true
case "seven": return true
case "eight": return true
case "nine": return true
default: return false
}
switch secondNumber {
case "zero": return false
case "one": return false
case "two": return false
case "three": return false
case "four": return false
case "five": return false
case "six": return false
case "seven": return false
case "eight": return false
case "nine": return false
default: return false
}
}
return sortedNumbers.joined(separator: " ")
}
```
switch secondNumber { // will never be executed
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersDictionary = [
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9
]
let sortedNumbersArray = numbersArray.sorted {
numbersDictionary[$0]! < numbersDictionary[$1]!
}
return sortedNumbersArray.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 numbersArray = numbers.components(separatedBy: " ")
let numbersDictionary = [
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9
]
let sortedNumbersArray = numbersArray.sorted {
numbersDictionary[$0]! < numbersDictionary[$1]!
}
return sortedNumbersArray.joined(separator: " ")
}
```
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numberals = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
var sortedNumbersArray: [String] = []
var sortedNumbersString: String = ""
for number in numbersArray {
if let numberIndex = numberals.firstIndex(of: number) {
sortedNumbersArray.append(numberals[numberIndex])
}
}
sortedNumbersArray.sort()
for number in sortedNumbersArray {
if let numberIndex = numberals.firstIndex(of: number) {
sortedNumbersString += "\(numberals[numberIndex]) "
}
}
return sortedNumbersString
}
```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 numbersArray = numbers.components(separatedBy: " ")
let numberals = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
var sortedNumbersArray: [String] = []
var sortedNumbersString: String = ""
for number in numbersArray {
if let numberIndex = numberals.firstIndex(of: number) {
sortedNumbersArray.append(numberals[numberIndex])
}
}
sortedNumbersArray.sort()
for number in sortedNumbersArray {
if let numberIndex = numberals.firstIndex(of: number) {
sortedNumbersString += "\(numberals[numberIndex]) "
}
}
return sortedNumbersString
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.split(separator: " ")
let numberals = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
var numberalsDict = [String: Int]()
for (index, numberal) in numberals.enumerated() {
numberalsDict[numberal] = index
}
var sortedNumbersArray = [String]()
for number in numbersArray {
sortedNumbersArray.append(numberals[numberalsDict[String(number)]!])
}
return sortedNumbersArray.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 numbersArray = numbers.split(separator: " ")
let numberals = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
var numberalsDict = [String: Int]()
for (index, numberal) in numberals.enumerated() {
numberalsDict[numberal] = index
}
var sortedNumbersArray = [String]()
for number in numbersArray {
sortedNumbersArray.append(numberals[numberalsDict[String(number)]!])
}
return sortedNumbersArray.sorted().joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.split(separator: " ")
var numbersDictionary = [String: String]()
for number in numbersArray {
numbersDictionary[String(number)] = number
}
let sortedNumbers = numbersDictionary.keys.sorted { $0 < $1 }
var sortedNumbersString = ""
for number in sortedNumbers {
sortedNumbersString += "\(number) "
}
return sortedNumbersString.trimmingCharacters(in: .whitespaces)
}
```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 numbersArray = numbers.split(separator: " ")
var numbersDictionary = [String: String]()
for number in numbersArray {
numbersDictionary[String(number)] = number
}
let sortedNumbers = numbersDictionary.keys.sorted { $0 < $1 }
var sortedNumbersString = ""
for number in sortedNumbers {
sortedNumbersString += "\(number) "
}
return sortedNumbersString.trimmingCharacters(in: .whitespaces)
}
```
numbersDictionary[String(number)] = number // cannot assign value of type 'String.SubSequence' (aka 'Substring') to type 'String?'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let midIndex = sortedNumbers.count / 2
let leftIndex = midIndex - 1
let rightIndex = midIndex + 1
let leftValue = sortedNumbers[leftIndex]
let rightValue = sortedNumbers[rightIndex]
return (leftValue, rightValue)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let midIndex = sortedNumbers.count / 2
let leftIndex = midIndex - 1
let rightIndex = midIndex + 1
let leftValue = sortedNumbers[leftIndex]
let rightValue = sortedNumbers[rightIndex]
return (leftValue, rightValue)
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closestElements = (Double.infinity, Double.infinity)
for i in 0..<numbers.count-1 {
let currentDistance = numbers[i] - numbers[i+1]
if currentDistance < 0 {
currentDistance * -1
}
if currentDistance < closestElements.0 - closestElements.1 {
closestElements = (numbers[i], numbers[i+1])
}
}
return closestElements
}
```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 closestElements = (Double.infinity, Double.infinity)
for i in 0..<numbers.count-1 {
let currentDistance = numbers[i] - numbers[i+1]
if currentDistance < 0 {
currentDistance * -1
}
if currentDistance < closestElements.0 - closestElements.1 {
closestElements = (numbers[i], numbers[i+1])
}
}
return closestElements
}
```
currentDistance * -1 // result of operator '*' is unused
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closestElements = (Double.infinity, Double.infinity)
for i in 0 ..< numbers.count - 1 {
let currentElements = (numbers[i], numbers[i + 1])
let currentDistance = abs(currentElements.0 - currentElements.1)
let closestDistance = abs(closestElements.0 - closestElements.1)
if currentDistance < closestDistance {
closestElements = currentElements
}
}
return closestElements
}
```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 closestElements = (Double.infinity, Double.infinity)
for i in 0 ..< numbers.count - 1 {
let currentElements = (numbers[i], numbers[i + 1])
let currentDistance = abs(currentElements.0 - currentElements.1)
let closestDistance = abs(closestElements.0 - closestElements.1)
if currentDistance < closestDistance {
closestElements = currentElements
}
}
return closestElements
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Implement
}
```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
}
```
} // 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 0..<numbers.count-1 {
for j in i+1..<numbers.count {
if numbers[j] - numbers[i] < closest.1 - closest.0 {
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])
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
if numbers[j] - numbers[i] < closest.1 - closest.0 {
closest = (numbers[i], numbers[j])
}
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Implement this function.
return (0.0, 0.0)
}
```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.
return (0.0, 0.0)
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
var closestPair = (sortedNumbers[0], sortedNumbers[1])
for i in 0...sortedNumbers.count - 2 {
if sortedNumbers[i + 1] - sortedNumbers[i] < closestPair.1 - closestPair.0 {
closestPair = (sortedNumbers[i], sortedNumbers[i + 1])
}
}
return closestPair
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
var closestPair = (sortedNumbers[0], sortedNumbers[1])
for i in 0...sortedNumbers.count - 2 {
if sortedNumbers[i + 1] - sortedNumbers[i] < closestPair.1 - closestPair.0 {
closestPair = (sortedNumbers[i], sortedNumbers[i + 1])
}
}
return closestPair
}
```
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closestElements = (Double.infinity, Double.infinity)
for (index, number) in numbers.enumerated() {
if index == 0 {
closestElements = (number, number)
} else {
let difference = abs(number - numbers[index - 1])
if difference < closestElements.0 - closestElements.1 {
closestElements = (number, numbers[index - 1])
}
}
}
return closestElements
}
```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 closestElements = (Double.infinity, Double.infinity)
for (index, number) in numbers.enumerated() {
if index == 0 {
closestElements = (number, number)
} else {
let difference = abs(number - numbers[index - 1])
if difference < closestElements.0 - closestElements.1 {
closestElements = (number, numbers[index - 1])
}
}
}
return closestElements
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Implement me!
let sortedArray = numbers.sorted()
let first = sortedArray.first!
let last = sortedArray.last!
let mid = sortedArray.count / 2
let midValue = sortedArray[mid]
if midValue == first {
return (first, sortedArray[mid + 1])
} else if midValue == last {
return (sortedArray[mid - 1], last)
} else {
return (sortedArray[mid - 1], sortedArray[mid + 1])
}
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
// TODO: Implement me!
let sortedArray = numbers.sorted()
let first = sortedArray.first!
let last = sortedArray.last!
let mid = sortedArray.count / 2
let midValue = sortedArray[mid]
if midValue == first {
return (first, sortedArray[mid + 1])
} else if midValue == last {
return (sortedArray[mid - 1], last)
} else {
return (sortedArray[mid - 1], sortedArray[mid + 1])
}
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closestElements = (numbers[0], numbers[1])
for i in 0..<(numbers.count - 1) {
if (abs(numbers[i] - numbers[i + 1]) < abs(closestElements.0 - closestElements.1)) {
closestElements = (numbers[i], numbers[i + 1])
}
}
return closestElements
}
```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 closestElements = (numbers[0], numbers[1])
for i in 0..<(numbers.count - 1) {
if (abs(numbers[i] - numbers[i + 1]) < abs(closestElements.0 - closestElements.1)) {
closestElements = (numbers[i], numbers[i + 1])
}
}
return closestElements
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
var result: [Double] = []
let min = numbers.min() ?? 0.0
let max = numbers.max() ?? 0.0
if min == max {
return numbers
}
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 result: [Double] = []
let min = numbers.min() ?? 0.0
let max = numbers.max() ?? 0.0
if min == max {
return numbers
}
for number in numbers {
result.append((number - min) / (max - min))
}
return result
}
```
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] {
guard numbers.count > 1 else { return numbers }
let min = numbers.min() ?? 0
let max = numbers.max() ?? 0
guard min != max else { return numbers }
return numbers.map { ($0 - min) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else { return numbers }
let min = numbers.min() ?? 0
let max = numbers.max() ?? 0
guard min != max else { return numbers }
return numbers.map { ($0 - min) / (max - min) }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
var numbers = numbers
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
var numbers = numbers
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
```
var numbers = numbers // variable 'numbers' was never mutated; consider changing to 'let' constant
func rescaleToUnit(numbers: [Double]) -> [Double] {
var numbers = numbers
numbers.sort()
let min = numbers.first ?? 0
let max = numbers.last ?? 0
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] {
var numbers = numbers
numbers.sort()
let min = numbers.first ?? 0
let max = numbers.last ?? 0
let range = max - min
return numbers.map { ($0 - min) / range }
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
var numbers = numbers
let min = numbers.min()!
let max = numbers.max()!
for i in 0..<numbers.count {
numbers[i] = (numbers[i] - min) / (max - min)
}
return numbers
}
```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 numbers = numbers
let min = numbers.min()!
let max = numbers.max()!
for i in 0..<numbers.count {
numbers[i] = (numbers[i] - min) / (max - min)
}
return numbers
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else { return numbers }
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] {
guard numbers.count > 1 else { return numbers }
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { ($0 - min) / range }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
var rescaled = numbers
let max = numbers.max()!
let min = numbers.min()!
for i in 0..<rescaled.count {
rescaled[i] = (rescaled[i] - min) / (max - min)
}
return rescaled
}
```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 rescaled = numbers
let max = numbers.max()!
let min = numbers.min()!
for i in 0..<rescaled.count {
rescaled[i] = (rescaled[i] - min) / (max - min)
}
return rescaled
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
var res = [Double]()
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
for num in numbers {
let scaled = (num - min) / range
res.append(scaled)
}
return res
}
```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 res = [Double]()
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
for num in numbers {
let scaled = (num - min) / range
res.append(scaled)
}
return res
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var intArray = [Int]()
for value in values {
if let int = value as? Int {
intArray.append(int)
}
}
return intArray
}
```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 intArray = [Int]()
for value in values {
if let int = value as? Int {
intArray.append(int)
}
}
return intArray
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var integers = [Int]()
for value in values {
if let integer = value as? Int {
integers.append(integer)
}
}
return integers
}
```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 integers = [Int]()
for value in values {
if let integer = value as? Int {
integers.append(integer)
}
}
return integers
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
var filteredIntegers = [Int]()
for value in values {
if let integer = value as? Int {
filteredIntegers.append(integer)
}
}
return filteredIntegers
}
```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 filteredIntegers = [Int]()
for value in values {
if let integer = value as? Int {
filteredIntegers.append(integer)
}
}
return filteredIntegers
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
// Write your code here
var array = [Int]()
for value in values {
if value is Int {
array.append(value as! Int)
}
}
return array
}
```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] {
// Write your code here
var array = [Int]()
for value in values {
if value is Int {
array.append(value as! Int)
}
}
return array
}
```
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] {
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] {
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] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[Int]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
var filteredIntegers = [Int]()
for value in values {
if let integerValue = value as? Int {
filteredIntegers.append(integerValue)
}
}
return filteredIntegers
}
```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 filteredIntegers = [Int]()
for value in values {
if let integerValue = value as? Int {
filteredIntegers.append(integerValue)
}
}
return filteredIntegers
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
// TODO: Implement this function
return []
}
```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] {
// TODO: Implement this function
return []
}
```
// XCTAssertTrue failed
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
return string.characters.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
```
return string.characters.count // 'characters' is unavailable: Please use String directly
func largestDivisor(n: Int) -> Int {
var divisor = 0
for i in stride(from: n-1, to: 0, by: -1) {
if n % i == 0 {
divisor = i
break
}
}
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 = 0
for i in stride(from: n-1, to: 0, by: -1) {
if n % i == 0 {
divisor = i
break
}
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
var divisor = 1
var i = 2
while i < n {
if n % i == 0 {
divisor = i
}
i += 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 = 1
var i = 2
while i < n {
if n % i == 0 {
divisor = i
}
i += 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 largestDivisor(n: Int) -> Int {
var divisor = 0
var i = n - 1
while i > 0 {
if n % i == 0 {
divisor = i
break
}
i -= 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 = 0
var i = n - 1
while i > 0 {
if n % i == 0 {
divisor = i
break
}
i -= 1
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1..<n {
if n % i == 0 {
divisor = i
}
}
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 = 1
for i in 1..<n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
var divisor = n / 2
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 / 2
while divisor > 1 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return 1
}
```
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1...n/2 {
if n % i == 0 {
divisor = i
}
}
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 = 1
for i in 1...n/2 {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in stride(from: n - 1, to: 1, by: -1) {
if n % i == 0 {
divisor = i
break
}
}
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 = 1
for i in stride(from: n - 1, to: 1, by: -1) {
if n % i == 0 {
divisor = i
break
}
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
var divisor = 0
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
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 = 0
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n / 2
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 / 2
while divisor > 0 {
if n % divisor == 0 {
return divisor
}
divisor -= 1
}
return -1
}
```
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var i = 2
while number > 1 {
if number % i == 0 {
result.append(i)
number /= i
} else {
i += 1
}
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var i = 2
while number > 1 {
if number % i == 0 {
result.append(i)
number /= i
} else {
i += 1
}
}
return result
}
```
func factorize(n: Int) -> [Int] {
var result = [Int]()
var number = n
var factor = 2
while number > 1 {
if number % factor == 0 {
result.append(factor)
number /= factor
} else {
factor += 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 factor = 2
while number > 1 {
if number % factor == 0 {
result.append(factor)
number /= factor
} else {
factor += 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 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 divisor = 2
while divisor <= number {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
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 divisor <= number {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
number /= divisor
factors.append(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 {
number /= divisor
factors.append(divisor)
}
divisor += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
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 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var n = n
var factors: [Int] = []
var i = 2
while i * i <= n {
while n % i == 0 {
n /= i
factors.append(i)
}
i += 1
}
if n > 1 {
factors.append(n)
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var n = n
var factors: [Int] = []
var i = 2
while i * i <= n {
while n % i == 0 {
n /= i
factors.append(i)
}
i += 1
}
if n > 1 {
factors.append(n)
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
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 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
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 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for num in numbers {
if !result.contains(num) {
result.append(num)
}
}
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 num in numbers {
if !result.contains(num) {
result.append(num)
}
}
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
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var uniqueNumbers: [Int] = []
var uniqueNumbersSet: Set<Int> = []
for number in numbers {
if !uniqueNumbersSet.contains(number) {
uniqueNumbers.append(number)
uniqueNumbersSet.insert(number)
}
}
return uniqueNumbers
}
```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 uniqueNumbers: [Int] = []
var uniqueNumbersSet: Set<Int> = []
for number in numbers {
if !uniqueNumbersSet.contains(number) {
uniqueNumbers.append(number)
uniqueNumbersSet.insert(number)
}
}
return uniqueNumbers
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result: [Int] = []
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result: [Int] = []
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result: [Int] = []
var seen: Set<Int> = []
for number in numbers {
if !seen.contains(number) {
seen.insert(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] = []
var seen: Set<Int> = []
for number in numbers {
if !seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.contains(number) == false {
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) == false {
result.append(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
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for num in numbers {
if !result.contains(num) {
result.append(num)
}
}
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 num in numbers {
if !result.contains(num) {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for num in numbers {
if result.contains(num) {
continue
}
result.append(num)
}
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 num in numbers {
if result.contains(num) {
continue
}
result.append(num)
}
return result
}
```
// XCTAssertTrue failed
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return $0.lowercased()
} else {
return $0.uppercased()
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return $0.lowercased()
} else {
return $0.uppercased()
}
}.joined()
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(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 += String(char).uppercased()
} else {
result += String(char).lowercased()
}
}
return result
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return $0.lowercaseString
} else {
return $0.uppercaseString
}
}.joinWithSeparator("")
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return $0.lowercaseString
} else {
return $0.uppercaseString
}
}.joinWithSeparator("")
}
```
return $0.lowercaseString // value of type 'String.Element' (aka 'Character') has no member 'lowercaseString'
}.joinWithSeparator("") // value of type 'Array<_>' has no member 'joinWithSeparator'
func flipCase(string: String) -> String {
let characters = Array(string)
return characters.map {
switch $0 {
case "a"..."z":
return $0.uppercased()
case "A"..."Z":
return $0.lowercased()
default:
return $0
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let characters = Array(string)
return characters.map {
switch $0 {
case "a"..."z":
return $0.uppercased()
case "A"..."Z":
return $0.lowercased()
default:
return $0
}
}.joined()
}
```
return $0 // cannot convert value of type 'String.Element' (aka 'Character') to closure result type 'String'
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return $0.lowercaseString
} else {
return $0.uppercaseString
}
}.joinWithSeparator("")
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return $0.lowercaseString
} else {
return $0.uppercaseString
}
}.joinWithSeparator("")
}
```
return $0.lowercaseString // value of type 'String.Element' (aka 'Character') has no member 'lowercaseString'
}.joinWithSeparator("") // value of type 'Array<_>' has no member 'joinWithSeparator'
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
}.joined()
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
}.joined()
}
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString.append(char.uppercased())
} else {
newString.append(char.lowercased())
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString.append(char.uppercased())
} else {
newString.append(char.lowercased())
}
}
return newString
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
}.joined()
}
```
func flipCase(string: String) -> String {
let lowerCase = "abcdefghijklmnopqrstuvwxyz"
let upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var newString = ""
for char in string {
if lowerCase.contains(char) {
newString.append(upperCase[upperCase.index(of: char)!])
} else if upperCase.contains(char) {
newString.append(lowerCase[lowerCase.index(of: char)!])
} else {
newString.append(char)
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let lowerCase = "abcdefghijklmnopqrstuvwxyz"
let upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var newString = ""
for char in string {
if lowerCase.contains(char) {
newString.append(upperCase[upperCase.index(of: char)!])
} else if upperCase.contains(char) {
newString.append(lowerCase[lowerCase.index(of: char)!])
} else {
newString.append(char)
}
}
return newString
}
```
newString.append(upperCase[upperCase.index(of: char)!]) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
newString.append(lowerCase[lowerCase.index(of: char)!]) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
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 {
// TODO: Implement this function
return ""
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
// TODO: Implement this function
return ""
}
```
// XCTAssertTrue failed
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 {
// TODO: Implement this function
return ""
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
// TODO: Implement this function
return ""
}
```
// XCTAssertTrue failed
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 str in strings {
result += str
}
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 str in strings {
result += str
}
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] {
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] {
return strings.filter { $0.starts(with: 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.starts(with: 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] {
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] {
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] {
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 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 }
}
```
// XCTAssertTrue failed
func getPositive(l: [Int]) -> [Int] {
var positiveNumbers = [Int]()
for number in l {
if number >= 0 {
positiveNumbers.append(number)
}
}
return positiveNumbers
}
```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 positiveNumbers = [Int]()
for number in l {
if number >= 0 {
positiveNumbers.append(number)
}
}
return positiveNumbers
}
```
// XCTAssertTrue failed
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 }
}
```
// XCTAssertTrue failed
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 }
}
```
// XCTAssertTrue failed
func getPositive(l: [Int]) -> [Int] {
var positiveNumbers = [Int]()
for number in l {
if number > 0 {
positiveNumbers.append(number)
}
}
return positiveNumbers
}
```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 positiveNumbers = [Int]()
for number in l {
if number > 0 {
positiveNumbers.append(number)
}
}
return positiveNumbers
}
```
func getPositive(l: [Int]) -> [Int] {
var positiveNumbers: [Int] = []
for number in l {
if number > 0 {
positiveNumbers.append(number)
}
}
return positiveNumbers
}
```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 positiveNumbers: [Int] = []
for number in l {
if number > 0 {
positiveNumbers.append(number)
}
}
return positiveNumbers
}
```
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 getPositive(l: [Int]) -> [Int] {
var pos = [Int]()
for i in l {
if i > 0 {
pos.append(i)
}
}
return pos
}
```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 pos = [Int]()
for i in l {
if i > 0 {
pos.append(i)
}
}
return pos
}
```
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 isPrime(n: Int) -> Bool {
guard n > 1 else { return false }
guard n != 2 else { return true }
guard n % 2 != 0 else { return false }
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
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 }
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in stride(from: 3, through: n / 2, 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 {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in stride(from: 3, through: n / 2, by: 2) {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in stride(from: 3, through: n / 2, 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 {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in stride(from: 3, through: n / 2, by: 2) {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
break
}
}
return isPrime
}
```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 {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
break
}
}
return isPrime
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isPrime(n: Int) -> Bool {
var isPrime = true
if n <= 1 {
isPrime = false
} else if n <= 3 {
isPrime = true
} else if n % 2 == 0 || n % 3 == 0 {
isPrime = false
} else {
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
isPrime = false
}
i = i + 6
}
}
return isPrime
}
```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 {
var isPrime = true
if n <= 1 {
isPrime = false
} else if n <= 3 {
isPrime = true
} else if n % 2 == 0 || n % 3 == 0 {
isPrime = false
} else {
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
isPrime = false
}
i = i + 6
}
}
return isPrime
}
```
func isPrime(n: Int) -> Bool {
var isPrime = true
if n <= 1 {
isPrime = false
} else {
for i in 2...n/2 {
if n % i == 0 {
isPrime = false
break
}
}
}
return isPrime
}
```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 {
var isPrime = true
if n <= 1 {
isPrime = false
} else {
for i in 2...n/2 {
if n % i == 0 {
isPrime = false
break
}
}
}
return isPrime
}
```
func isPrime(n: Int) -> Bool {
if n == 1 { return false }
if n == 2 { return true }
let sqrtN = Int(sqrt(Double(n)))
for i in 2...sqrtN {
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 }
if n == 2 { return true }
let sqrtN = Int(sqrt(Double(n)))
for i in 2...sqrtN {
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 {
// TODO: Implement me!
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
// TODO: Implement me!
if n < 2 {
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 sortThird(l: [Int]) -> [Int] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Int]'
func sortThird(l: [Int]) -> [Int] {
// TODO: implement this function
var lPrime = l
for i in 0...l.count - 1 {
if i % 3 == 0 {
let temp = l[i]
for j in i + 1...l.count - 1 {
if l[j] < temp {
lPrime[j - 1] = l[j]
} else {
lPrime[j - 1] = temp
}
}
}
}
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] {
// TODO: implement this function
var lPrime = l
for i in 0...l.count - 1 {
if i % 3 == 0 {
let temp = l[i]
for j in i + 1...l.count - 1 {
if l[j] < temp {
lPrime[j - 1] = l[j]
} else {
lPrime[j - 1] = temp
}
}
}
}
return lPrime
}
```
// Fatal error: Range requires lowerBound <= upperBound
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in stride(from: l.count - 1, to: 0, by: -1) {
if i % 3 == 0 {
l.swapAt(i, l.index(i, offsetBy: -1))
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in stride(from: l.count - 1, to: 0, by: -1) {
if i % 3 == 0 {
l.swapAt(i, l.index(i, offsetBy: -1))
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
// TODO: implement
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] {
// TODO: implement
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
// TODO: implement this function
}
```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] {
// TODO: implement this function
}
```
} // missing return in global function expected to return '[Int]'
func sortThird(l: [Int]) -> [Int] {
let l = l.filter { $0 % 3 != 0 }
let l = l.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] {
let l = l.filter { $0 % 3 != 0 }
let l = l.sorted()
return l
}
```
let l = l.sorted() // invalid redeclaration of 'l'
func sortThird(l: [Int]) -> [Int] {
let l = l
var l2 = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
l2.append(l[i])
}
}
l2.sort()
var l3 = [Int]()
var j = 0
for i in 0..<l.count {
if i % 3 == 0 {
l3.append(l2[j])
j += 1
} else {
l3.append(l[i])
}
}
return l3
}
```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] {
let l = l
var l2 = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
l2.append(l[i])
}
}
l2.sort()
var l3 = [Int]()
var j = 0
for i in 0..<l.count {
if i % 3 == 0 {
l3.append(l2[j])
j += 1
} else {
l3.append(l[i])
}
}
return l3
}
```
func sortThird(l: [Int]) -> [Int] {
return l.map { $0 % 3 != 0 ? $0 : l.sorted()[l.firstIndex(of: $0)!] }
}
```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] {
return l.map { $0 % 3 != 0 ? $0 : l.sorted()[l.firstIndex(of: $0)!] }
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var l_prime = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
l_prime.append(l[i])
}
}
l_prime.sort()
return l_prime
}
```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 l_prime = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
l_prime.append(l[i])
}
}
l_prime.sort()
return l_prime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
return l.map { $0 }
}
```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] {
return l.map { $0 }
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
return l.sort().reduce([], { (acc, i) -> [Int] in
if acc.last == i {
return acc
} else {
return acc + [i]
}
})
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sort().reduce([], { (acc, i) -> [Int] in
if acc.last == i {
return acc
} else {
return acc + [i]
}
})
}
```
return l.sort().reduce([], { (acc, i) -> [Int] in // cannot use mutating member on immutable value: 'l' is a 'let' constant
return l.sort().reduce([], { (acc, i) -> [Int] in // value of tuple type '()' has no member 'reduce'
func unique(l: [Int]) -> [Int] {
var result: [Int] = []
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result: [Int] = []
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
return l.filter { (x) -> Bool in
return l.count(of: x) == 1
}
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.filter { (x) -> Bool in
return l.count(of: x) == 1
}
}
```
return l.count(of: x) == 1 // cannot call value of non-function type 'Int'
func unique(l: [Int]) -> [Int] {
var result: [Int] = []
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
```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.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
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
return Array(Set(l)).sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return Array(Set(l)).sorted()
}
```
func unique(l: [Int]) -> [Int] {
var unique: [Int] = []
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```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.sorted()
}
```
func unique(l: [Int]) -> [Int] {
return l.filter { (x) -> Bool in
return l.filter { $0 == x }.count == 1
}
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.filter { (x) -> Bool in
return l.filter { $0 == x }.count == 1
}
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in 0..<l.count {
if !unique.contains(l[i]) {
unique.append(l[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 0..<l.count {
if !unique.contains(l[i]) {
unique.append(l[i])
}
}
return unique
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique: [Int] = []
for i in 0..<l.count {
if unique.contains(l[i]) == false {
unique.append(l[i])
}
}
unique.sort()
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 0..<l.count {
if unique.contains(l[i]) == false {
unique.append(l[i])
}
}
unique.sort()
return unique
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 0...l.count-1 {
if max < l[i] {
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 0...l.count-1 {
if max < l[i] {
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 maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 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 {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i.contains(7) {
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 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i.contains(7) {
count += 1
}
}
return count
}
```
if (i % 11 == 0 || i % 13 == 0) && i.contains(7) { // value of type 'Int' has no member 'contains'
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
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 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0...n - 1 {
if i % 11 == 0 || i % 13 == 0 {
if i % 10 == 7 {
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 0...n - 1 {
if i % 11 == 0 || i % 13 == 0 {
if i % 10 == 7 {
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) && i.description.contains("7") {
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) && i.description.contains("7") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n-1 {
if i % 11 == 0 || i % 13 == 0 {
let str = "\(i)"
for j in 0...str.count-1 {
if str[j] == "7" {
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-1 {
if i % 11 == 0 || i % 13 == 0 {
let str = "\(i)"
for j in 0...str.count-1 {
if str[j] == "7" {
count += 1
}
}
}
}
return count
}
```
if str[j] == "7" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
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) && i % 10 == 7 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n-1 {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
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-1 {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0...n - 1 {
if i % 11 == 0 || i % 13 == 0 {
var temp = i
while temp > 0 {
if temp % 10 == 7 {
count += 1
}
temp /= 10
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0...n - 1 {
if i % 11 == 0 || i % 13 == 0 {
var temp = i
while temp > 0 {
if temp % 10 == 7 {
count += 1
}
temp /= 10
}
}
}
return count
}
```
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
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) && i % 10 == 7 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0...n - 1 {
if i % 11 == 0 || i % 13 == 0 {
count += String(i).filter({ $0 == "7" }).count
}
}
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 0...n - 1 {
if i % 11 == 0 || i % 13 == 0 {
count += String(i).filter({ $0 == "7" }).count
}
}
return count
}
```
func sortEven(l: [Int]) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func sortEven(l: [Int]) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func sortEven(l: [Int]) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func sortEven(l: [Int]) -> [Int] {
var lPrime: [Int] = []
for i in 0..<l.count {
if i % 2 == 0 {
lPrime.append(l[i])
}
}
lPrime.sort()
for i in 0..<l.count {
if i % 2 == 1 {
lPrime.insert(l[i], at: i)
}
}
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: [Int] = []
for i in 0..<l.count {
if i % 2 == 0 {
lPrime.append(l[i])
}
}
lPrime.sort()
for i in 0..<l.count {
if i % 2 == 1 {
lPrime.insert(l[i], at: i)
}
}
return lPrime
}
```
func sortEven(l: [Int]) -> [Int] {
// TODO: Implement this function
var l1 = l
var l2 = l
var l3 = [Int]()
var l4 = [Int]()
for i in 0...l1.count-1 {
if i%2==0 {
l3.append(l1[i])
}
else {
l4.append(l1[i])
}
}
l3.sort()
for i in 0...l3.count-1 {
l2[i*2] = l3[i]
}
for i in 0...l4.count-1 {
l2[i*2+1] = l4[i]
}
return l2
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
// TODO: Implement this function
var l1 = l
var l2 = l
var l3 = [Int]()
var l4 = [Int]()
for i in 0...l1.count-1 {
if i%2==0 {
l3.append(l1[i])
}
else {
l4.append(l1[i])
}
}
l3.sort()
for i in 0...l3.count-1 {
l2[i*2] = l3[i]
}
for i in 0...l4.count-1 {
l2[i*2+1] = l4[i]
}
return l2
}
```
var l1 = l // variable 'l1' was never mutated; consider changing to 'let' constant
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
if l[i] > l[i + 1] {
l.swapAt(i, i + 1)
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
if l[i] > l[i + 1] {
l.swapAt(i, i + 1)
}
}
return l
}
```
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
var l2 = l
var l3 = l2.filter{ $0 % 2 == 1 }
for i in 0 ..< l2.count {
if l2[i] % 2 == 0 {
l3.append(l2[i])
}
}
return l3.sorted()
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l2 = l
var l3 = l2.filter{ $0 % 2 == 1 }
for i in 0 ..< l2.count {
if l2[i] % 2 == 0 {
l3.append(l2[i])
}
}
return l3.sorted()
}
```
var l2 = l // variable 'l2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l = l
var l2 = l
for i in 0...l.count-1 {
if i%2 == 0 {
l2.insert(l[i], at: i)
l.remove(at: i)
}
}
return l2
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var l2 = l
for i in 0...l.count-1 {
if i%2 == 0 {
l2.insert(l[i], at: i)
l.remove(at: i)
}
}
return l2
}
```
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
// TODO: Implement this function
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] {
// TODO: Implement this function
return l
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
if l[i] > l[i+1] {
let temp = l[i]
l[i] = l[i+1]
l[i+1] = temp
}
}
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) {
if l[i] > l[i+1] {
let temp = l[i]
l[i] = l[i+1]
l[i+1] = temp
}
}
return l
}
```
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while i < n {
let nextFib = fib[i - 1] + fib[i - 2]
fib.append(nextFib)
i += 1
}
let fibs = fib.filter { isPrime($0) }
return fibs[n - 1]
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while i < n {
let nextFib = fib[i - 1] + fib[i - 2]
fib.append(nextFib)
i += 1
}
let fibs = fib.filter { isPrime($0) }
return fibs[n - 1]
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
print(primeFib(n: 1))
print(primeFib(n: 2))
print(primeFib(n: 3))
print(primeFib(n: 4))
print(primeFib(n: 5))
```
let fibs = fib.filter { isPrime($0) } // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var fibs: [Int] = [0, 1]
var primes: [Int] = []
var i = 2
while fibs.count < n {
fibs.append(fibs[i-2] + fibs[i-1])
if isPrime(fibs[i]) {
primes.append(fibs[i])
}
i += 1
}
return primes[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 fibs: [Int] = [0, 1]
var primes: [Int] = []
var i = 2
while fibs.count < n {
fibs.append(fibs[i-2] + fibs[i-1])
if isPrime(fibs[i]) {
primes.append(fibs[i])
}
i += 1
}
return primes[n - 1]
}
```
if isPrime(fibs[i]) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib.count <= n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
for i in 0..<fib.count {
if isPrime(n: fib[i]) {
return fib[i]
}
}
return fib[fib.count - 1]
}
func isPrime(n: Int) -> Bool {
if n == 2 {
return true
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib.count <= n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
for i in 0..<fib.count {
if isPrime(n: fib[i]) {
return fib[i]
}
}
return fib[fib.count - 1]
}
// isPrime returns true if n is prime number.
// isPrime(n: 2) == true
// isPrime(n: 3) == true
// isPrime(n: 4) == false
// isPrime(n: 5) == true
// isPrime(n: 6) == false
func isPrime(n: Int) -> Bool {
if n == 2 {
return true
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeFib(n: Int) -> Int {
var fibs: [Int] = []
var i = 1
while fibs.count < n {
if isPrime(n: i) {
fibs.append(i)
}
i += 1
}
return fibs[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 fibs: [Int] = []
var i = 1
while fibs.count < n {
if isPrime(n: i) {
fibs.append(i)
}
i += 1
}
return fibs[n - 1]
}
```
if isPrime(n: i) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fibs = [Int]()
fibs.append(0)
fibs.append(1)
var i = 2
while i < n {
fibs.append(fibs[i - 1] + fibs[i - 2])
i += 1
}
for fib in fibs.reverse() {
if isPrime(n: fib) {
return fib
}
}
return -1
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```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 fibs = [Int]()
fibs.append(0)
fibs.append(1)
var i = 2
while i < n {
fibs.append(fibs[i - 1] + fibs[i - 2])
i += 1
}
for fib in fibs.reverse() {
if isPrime(n: fib) {
return fib
}
}
return -1
}
// isPrime returns true if n is prime.
// isPrime(n: 2) == true
// isPrime(n: 3) == true
// isPrime(n: 4) == false
// isPrime(n: 5) == true
// isPrime(n: 6) == false
// isPrime(n: 7) == true
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
for fib in fibs.reverse() { // for-in loop requires '()' to conform to 'Sequence'
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib.count < n {
let nextFib = fib[i - 1] + fib[i - 2]
if nextFib.isPrime() {
fib.append(nextFib)
}
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 = [0, 1]
var i = 2
while fib.count < n {
let nextFib = fib[i - 1] + fib[i - 2]
if nextFib.isPrime() {
fib.append(nextFib)
}
i += 1
}
return fib[n - 1]
}
```
if nextFib.isPrime() { // value of type 'Int' has no member 'isPrime'
func primeFib(n: Int) -> Int {
var fibs = [0, 1]
var i = 2
while i <= n {
let next = fibs[i - 1] + fibs[i - 2]
fibs.append(next)
i += 1
}
for i in 0..<fibs.count {
if isPrime(n: fibs[i]) {
return fibs[i]
}
}
return -1
}
func isPrime(n: Int) -> Bool {
if n == 0 || n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```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 fibs = [0, 1]
var i = 2
while i <= n {
let next = fibs[i - 1] + fibs[i - 2]
fibs.append(next)
i += 1
}
for i in 0..<fibs.count {
if isPrime(n: fibs[i]) {
return fibs[i]
}
}
return -1
}
// isPrime returns true if n is a prime number, otherwise false.
func isPrime(n: Int) -> Bool {
if n == 0 || n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fibs = [Int]()
fibs.append(1)
fibs.append(2)
var i = 2
while fibs.count < n {
i += 1
let fib = fibs[i-2] + fibs[i-1]
fibs.append(fib)
}
return fibs[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 fibs = [Int]()
fibs.append(1)
fibs.append(2)
var i = 2
while fibs.count < n {
i += 1
let fib = fibs[i-2] + fibs[i-1]
fibs.append(fib)
}
return fibs[n-1]
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(1)
fib.append(2)
while fib.count < n {
let nextFib = fib[fib.count - 1] + fib[fib.count - 2]
fib.append(nextFib)
}
for i in fib {
if isPrime(n: i) {
return i
}
}
return -1
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```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]()
fib.append(1)
fib.append(2)
while fib.count < n {
let nextFib = fib[fib.count - 1] + fib[fib.count - 2]
fib.append(nextFib)
}
for i in fib {
if isPrime(n: i) {
return i
}
}
return -1
}
// isPrime returns true if n is prime.
// isPrime(n: 2) == true
// isPrime(n: 3) == true
// isPrime(n: 4) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [0, 1]
for _ in 0 ..< n {
fib.append(fib[fib.count - 2] + fib[fib.count - 1])
if isPrime(n: fib.last!) {
return fib.last!
}
}
return -1
}
func isPrime(n: Int) -> Bool {
if n <= 1 { return false }
if n == 2 { return true }
for i in 2 ..< Int(sqrt(Double(n))) {
if n % i == 0 { return false }
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
for _ in 0 ..< n {
fib.append(fib[fib.count - 2] + fib[fib.count - 1])
if isPrime(n: fib.last!) {
return fib.last!
}
}
return -1
}
// isPrime returns true if n is prime, false otherwise.
func isPrime(n: Int) -> Bool {
if n <= 1 { return false }
if n == 2 { return true }
for i in 2 ..< Int(sqrt(Double(n))) {
if n % i == 0 { return false }
}
return true
}
print(primeFib(n: 100))
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// your code here
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
}
```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
}
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: implement
}
```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
}
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: implement
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
return false
}
```
// XCTAssertTrue failed
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 {
// TODO: implement
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
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: your code here
}
```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: your code here
}
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: your code here
}
```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: your code here
}
```
} // 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 {
// TODO: Write your code here.
}
```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.
}
```
} // missing return in global function expected to return 'Bool'
```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 {
// The number of collisions is the number of pairs of cars that
// are moving in opposite directions.
// The number of pairs of cars that are moving in opposite directions
// is the number of cars that are moving left to right multiplied by the
// number of cars that are moving right to left.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to left.
// The number of cars that are moving right to left is the number of cars
// minus the number of cars that are moving left to right.
// The number of cars that are moving left to right is the number of cars
// minus the number of cars that are moving right to
XCTAssertTrue(carRaceCollision(n: 2) == 4) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 3) == 9) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 4) == 16) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 8) == 64) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 10) == 100) // cannot find 'carRaceCollision' in scope
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var leftToRight = [Int]()
var rightToLeft = [Int]()
for _ in 0..<n {
leftToRight.append(Int.random(in: 0..<10))
rightToLeft.append(Int.random(in: 0..<10))
}
for i in 0..<n {
for j in 0..<n {
if leftToRight[i] == rightToLeft[j] {
collisions += 1
}
}
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var leftToRight = [Int]()
var rightToLeft = [Int]()
for _ in 0..<n {
leftToRight.append(Int.random(in: 0..<10))
rightToLeft.append(Int.random(in: 0..<10))
}
for i in 0..<n {
for j in 0..<n {
if leftToRight[i] == rightToLeft[j] {
collisions += 1
}
}
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
// We can use a queue to store the cars that are moving left to right
// and a stack to store the cars that are moving right to left.
// We can then iterate through the queue and stack and compare the
// cars at the front of each queue/stack. If the cars collide, we
// can remove them from both queues/stacks and increment the collision
// counter. If the cars do not collide, we can remove the car from
// the front of the queue and push it onto the stack.
var leftToRightQueue = [Int]()
var rightToLeftStack = [Int]()
var collisionCount = 0
for i in 0..<n {
leftToRightQueue.append(i)
}
for i in 0..<n {
rightToLeftStack.append(i)
}
while !leftToRightQueue.isEmpty && !rightToLeftStack.isEmpty {
if leftToRightQueue[0] == rightToLeftStack[0] {
leftToRightQueue.remove(at: 0)
rightToLeftStack.remove(at: 0)
collisionCount += 1
} else {
leftToRightQueue.remove(at: 0)
rightToLeftStack.append(rightToLeftStack.remove(at: 0))
}
}
return collisionCount
}
```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 {
// We can use a queue to store the cars that are moving left to right
// and a stack to store the cars that are moving right to left.
// We can then iterate through the queue and stack and compare the
// cars at the front of each queue/stack. If the cars collide, we
// can remove them from both queues/stacks and increment the collision
// counter. If the cars do not collide, we can remove the car from
// the front of the queue and push it onto the stack.
var leftToRightQueue = [Int]()
var rightToLeftStack = [Int]()
var collisionCount = 0
for i in 0..<n {
leftToRightQueue.append(i)
}
for i in 0..<n {
rightToLeftStack.append(i)
}
while !leftToRightQueue.isEmpty && !rightToLeftStack.isEmpty {
if leftToRightQueue[0] == rightToLeftStack[0] {
leftToRightQueue.remove(at: 0)
rightToLeftStack.remove(at: 0)
collisionCount += 1
} else {
leftToRightQueue.remove(at: 0)
rightToLeftStack.append(rightToLeftStack.remove(at: 0))
}
}
return collisionCount
}
print(carRaceCollision(n: 5))
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 1
var right = n
while left < right {
collisions += 1
left += 1
right -= 1
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 1
var right = n
while left < right {
collisions += 1
left += 1
right -= 1
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var leftCars = Array(repeating: 0, count: n)
var rightCars = Array(repeating: 0, count: n)
for i in 0..<n {
leftCars[i] = i + 1
rightCars[i] = n - i
}
while leftCars.count > 0 && rightCars.count > 0 {
let left = leftCars.removeFirst()
let right = rightCars.removeLast()
if left == right {
collisions += 1
}
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var leftCars = Array(repeating: 0, count: n)
var rightCars = Array(repeating: 0, count: n)
for i in 0..<n {
leftCars[i] = i + 1
rightCars[i] = n - i
}
while leftCars.count > 0 && rightCars.count > 0 {
let left = leftCars.removeFirst()
let right = rightCars.removeLast()
if left == right {
collisions += 1
}
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var left: [Int] = []
var right: [Int] = []
var collisions = 0
for i in 0..<n {
left.append(i)
right.append(n - i - 1)
}
while left.count > 0 && right.count > 0 {
if left[0] == right[0] {
collisions += 1
left.removeFirst()
right.removeFirst()
} else if left[0] > right[0] {
left.removeFirst()
} else {
right.removeFirst()
}
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var left: [Int] = []
var right: [Int] = []
var collisions = 0
for i in 0..<n {
left.append(i)
right.append(n - i - 1)
}
while left.count > 0 && right.count > 0 {
if left[0] == right[0] {
collisions += 1
left.removeFirst()
right.removeFirst()
} else if left[0] > right[0] {
left.removeFirst()
} else {
right.removeFirst()
}
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var leftCars = [Int]()
var rightCars = [Int]()
var collisionCount = 0
// Create the left cars array and right cars array
for i in 0...n-1 {
leftCars.append(i)
rightCars.append(n-1-i)
}
// Iterate through the left cars array and right cars array
for i in 0...n-1 {
for j in 0...n-1 {
// Check if the left car and right car collide
if leftCars[i] == rightCars[j] {
// Increment the collision count
collisionCount += 1
// Remove the collided cars from the arrays
leftCars.remove(at: i)
rightCars.remove(at: j)
// Break the inner loop
break
}
}
}
// Return the collision count
return collisionCount
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var leftCars = [Int]()
var rightCars = [Int]()
var collisionCount = 0
// Create the left cars array and right cars array
for i in 0...n-1 {
leftCars.append(i)
rightCars.append(n-1-i)
}
// Iterate through the left cars array and right cars array
for i in 0...n-1 {
for j in 0...n-1 {
// Check if the left car and right car collide
if leftCars[i] == rightCars[j] {
// Increment the collision count
collisionCount += 1
// Remove the collided cars from the arrays
leftCars.remove(at: i)
rightCars.remove(at: j)
// Break the inner loop
break
}
}
}
// Return the collision count
return collisionCount
}
// Test the function
print(carRaceCollision(n: 5)) // Output: 10
```
// Fatal error: Index out of range
func carRaceCollision(n: Int) -> Int {
var left: [Int] = []
var right: [Int] = []
var count: Int = 0
for i in 0..<n {
left.append(i)
right.append(n - i - 1)
}
while left.count != 0 {
if left.count == right.count {
count += 1
left.remove(at: 0)
right.remove(at: 0)
} else if left.count > right.count {
count += 1
left.remove(at: 0)
} else {
count += 1
right.remove(at: 0)
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var left: [Int] = []
var right: [Int] = []
var count: Int = 0
for i in 0..<n {
left.append(i)
right.append(n - i - 1)
}
while left.count != 0 {
if left.count == right.count {
count += 1
left.remove(at: 0)
right.remove(at: 0)
} else if left.count > right.count {
count += 1
left.remove(at: 0)
} else {
count += 1
right.remove(at: 0)
}
}
return count
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var leftCars = [Int]()
var rightCars = [Int]()
for i in 0..<n {
leftCars.append(i)
rightCars.append(n-1-i)
}
while leftCars.count > 0 && rightCars.count > 0 {
if leftCars[0] < rightCars[0] {
leftCars.removeFirst()
} else if leftCars[0] > rightCars[0] {
rightCars.removeFirst()
} else {
collisions += 1
leftCars.removeFirst()
rightCars.removeFirst()
}
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var leftCars = [Int]()
var rightCars = [Int]()
for i in 0..<n {
leftCars.append(i)
rightCars.append(n-1-i)
}
while leftCars.count > 0 && rightCars.count > 0 {
if leftCars[0] < rightCars[0] {
leftCars.removeFirst()
} else if leftCars[0] > rightCars[0] {
rightCars.removeFirst()
} else {
collisions += 1
leftCars.removeFirst()
rightCars.removeFirst()
}
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var leftCars = Array(repeating: 0, count: n)
var rightCars = Array(repeating: 0, count: n)
// Initialize the left and right cars
for i in 0..<n {
leftCars[i] = i
rightCars[i] = n - 1 - i
}
// Move the cars until they collide
var collisionCount = 0
while !leftCars.isEmpty && !rightCars.isEmpty {
let leftCar = leftCars.removeFirst()
let rightCar = rightCars.removeFirst()
if leftCar == rightCar {
collisionCount += 1
} else {
leftCars.append(leftCar)
rightCars.append(rightCar)
}
}
return collisionCount
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var leftCars = Array(repeating: 0, count: n)
var rightCars = Array(repeating: 0, count: n)
// Initialize the left and right cars
for i in 0..<n {
leftCars[i] = i
rightCars[i] = n - 1 - i
}
// Move the cars until they collide
var collisionCount = 0
while !leftCars.isEmpty && !rightCars.isEmpty {
let leftCar = leftCars.removeFirst()
let rightCar = rightCars.removeFirst()
if leftCar == rightCar {
collisionCount += 1
} else {
leftCars.append(leftCar)
rightCars.append(rightCar)
}
}
return collisionCount
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func pairsSumToZero(l: [Int]) -> Bool {
for i in 0..<l.count {
for j in i..<l.count {
if i != j && l[i] + l[j] == 0 {
return true
}
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
for i in 0..<l.count {
for j in i..<l.count {
if i != j && l[i] + l[j] == 0 {
return true
}
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
if l.count < 2 {
return false
}
var seen = Set<Int>()
for i in 0..<l.count {
let complement = -l[i]
if seen.contains(complement) {
return true
}
seen.insert(l[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 {
if l.count < 2 {
return false
}
var seen = Set<Int>()
for i in 0..<l.count {
let complement = -l[i]
if seen.contains(complement) {
return true
}
seen.insert(l[i])
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = [Int: Bool]()
for num in l {
if let _ = seen[-num] {
return true
}
seen[num] = true
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = [Int: Bool]()
for num in l {
if let _ = seen[-num] {
return true
}
seen[num] = true
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for num in set {
let other = -num
if set.contains(other) && num != other {
return true
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for num in set {
let other = -num
if set.contains(other) && num != other {
return true
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0 ..< l.count {
for j in i + 1 ..< l.count {
if set.contains(-(l[i] + l[j])) {
return true
}
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0 ..< l.count {
for j in i + 1 ..< l.count {
if set.contains(-(l[i] + l[j])) {
return true
}
}
}
return false
}
```
// XCTAssertTrue failed
func pairsSumToZero(l: [Int]) -> Bool {
for i in 0..<l.count {
for j in i+1..<l.count {
if l[i] + l[j] == 0 {
return true
}
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
for i in 0..<l.count {
for j in i+1..<l.count {
if l[i] + l[j] == 0 {
return true
}
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
if l.count < 2 {
return false
}
var seen = Set<Int>()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(sum) {
return true
}
seen.insert(sum)
}
}
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 {
if l.count < 2 {
return false
}
var seen = Set<Int>()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```
// XCTAssertTrue failed
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 {
// TODO: implement this function
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 {
// TODO: implement this function
return false
}
```
// XCTAssertTrue failed
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: String = ""
var x = x
while x > 0 {
let remainder = x % base
x = x / base
if remainder > 9 {
result = String(Character(UnicodeScalar(65 + remainder - 10)!) + result)
} else {
result = String(remainder) + result
}
}
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: String = ""
var x = x
while x > 0 {
let remainder = x % base
x = x / base
if remainder > 9 {
result = String(Character(UnicodeScalar(65 + remainder - 10)!) + result)
} else {
result = String(remainder) + result
}
}
return result
}
```
result = String(Character(UnicodeScalar(65 + remainder - 10)!) + result) // cannot convert value of type 'Character' to expected argument type 'String'
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
result = String(x % base) + result
x = x / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
result = String(x % base) + result
x = x / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
let remainder = x % base
x = x / base
result = String(remainder) + result
}
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: String = ""
var x = x
while x > 0 {
let remainder = x % base
x = x / base
result = String(remainder) + result
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = "\(x % base)" + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = "\(x % base)" + result
x /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x = x / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x = x / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result: String = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp != 0 {
result = String(temp % base) + result
temp = temp / 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 temp = x
while temp != 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder: Int
var quotient = x
while quotient > 0 {
remainder = quotient % base
quotient = quotient / base
result = String(remainder) + result
}
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: Int
var quotient = x
while quotient > 0 {
remainder = quotient % base
quotient = quotient / base
result = String(remainder) + result
}
return result
}
```
func triangleArea(a: Int, h: Int) -> Double {
let area = Double(a * h) / 2
return area
}
```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 {
let area = Double(a * h) / 2
return area
}
```
func triangleArea(a: Int, h: Int) -> Double {
let area = Double(a) * Double(h) / 2
return area
}
```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 {
let area = Double(a) * Double(h) / 2
return area
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```
func triangleArea(a: Int, h: Int) -> Double {
let area = Double(a * h) / 2
return area
}
```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 {
let area = Double(a * h) / 2
return area
}
triangleArea(a: 5, h: 3)
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(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) * Double(h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
let area = Double(a * h) / 2
return area
}
```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 {
let area = Double(a * h) / 2
return area
}
print(triangleArea(a: 5, h: 3))
```
func triangleArea(a: Int, h: Int) -> Double {
let area = Double(a * h) / 2
return area
}
```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 {
let area = Double(a * h) / 2
return area
}
```
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
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given 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) * Double(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) * Double(h) / 2
}
```
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 || n == 2 {
return 0
}
if n == 3 {
return 2
}
var a = 0
var b = 0
var c = 2
var d = 0
var e = 0
for _ in 4...n {
e = a + b + c + d
a = b
b = c
c = d
d = e
}
return e
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 || n == 2 {
return 0
}
if n == 3 {
return 2
}
var a = 0
var b = 0
var c = 2
var d = 0
var e = 0
for _ in 4...n {
e = a + b + c + d
a = b
b = c
c = d
d = e
}
return e
}
```
func fib4(n: Int) -> Int {
if n <= 2 {
return 0
}
if n == 3 {
return 2
}
var fib4 = [0,0,2,0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n <= 2 {
return 0
}
if n == 3 {
return 2
}
var fib4 = [0,0,2,0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
if n < 2 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
var fib4 = [Int]()
fib4.append(0)
fib4.append(0)
fib4.append(2)
fib4.append(0)
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n < 2 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
var fib4 = [Int]()
fib4.append(0)
fib4.append(0)
fib4.append(2)
fib4.append(0)
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
}
```
func fib4(n: Int) -> Int {
if n < 2 {
return 0
}
if n == 2 {
return 2
}
var fib4Array = [Int](repeating: 0, count: n + 1)
fib4Array[2] = 2
fib4Array[3] = 0
for i in 4...n {
fib4Array[i] = fib4Array[i-1] + fib4Array[i-2] + fib4Array[i-3] + fib4Array[i-4]
}
return fib4Array[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n < 2 {
return 0
}
if n == 2 {
return 2
}
var fib4Array = [Int](repeating: 0, count: n + 1)
fib4Array[2] = 2
fib4Array[3] = 0
for i in 4...n {
fib4Array[i] = fib4Array[i-1] + fib4Array[i-2] + fib4Array[i-3] + fib4Array[i-4]
}
return fib4Array[n]
}
```
func fib4(n: Int) -> Int {
// TODO: Write your code here.
var fib4 = [0, 0, 2, 0]
if n <= 3 {
return fib4[n]
}
for i in 4...n {
fib4.append(fib4[i - 1] + fib4[i - 2] + fib4[i - 3] + fib4[i - 4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
// TODO: Write your code here.
var fib4 = [0, 0, 2, 0]
if n <= 3 {
return fib4[n]
}
for i in 4...n {
fib4.append(fib4[i - 1] + fib4[i - 2] + fib4[i - 3] + fib4[i - 4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4 ... n {
fib4.append(fib4[i - 1] + fib4[i - 2] + fib4[i - 3] + fib4[i - 4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4 ... n {
fib4.append(fib4[i - 1] + fib4[i - 2] + fib4[i - 3] + fib4[i - 4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
// TODO: Implement this function.
var fib4 = [0,0,2,0]
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
// TODO: Implement this function.
var fib4 = [0,0,2,0]
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4 ... n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4 ... n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
// TODO: Implement me!
var fib4 = [Int](repeating: 0, count: n+1)
fib4[2] = 2
for i in 3...n {
fib4[i] = fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4]
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
// TODO: Implement me!
var fib4 = [Int](repeating: 0, count: n+1)
fib4[2] = 2
for i in 3...n {
fib4[i] = fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4]
}
return fib4[n]
}
```
// Fatal error: Index out of range
func median(l: [Int]) -> Double {
var l = l
l.sortInPlace()
let count = l.count
if count % 2 == 0 {
return (Double(l[count/2]) + Double(l[count/2 - 1])) / 2
} else {
return Double(l[count/2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
var l = l
l.sortInPlace()
let count = l.count
if count % 2 == 0 {
return (Double(l[count/2]) + Double(l[count/2 - 1])) / 2
} else {
return Double(l[count/2])
}
}
```
l.sortInPlace() // value of type '[Int]' has no member 'sortInPlace'
func median(l: [Int]) -> Double {
// TODO
}
```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
}
```
} // missing return in global function expected to return 'Double'
func median(l: [Int]) -> Double {
var l = l
l.sortInPlace()
let count = l.count
if count % 2 == 0 {
return (Double(l[count/2 - 1]) + Double(l[count/2])) / 2.0
} else {
return Double(l[count/2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
var l = l
l.sortInPlace()
let count = l.count
if count % 2 == 0 {
return (Double(l[count/2 - 1]) + Double(l[count/2])) / 2.0
} else {
return Double(l[count/2])
}
}
```
l.sortInPlace() // value of type '[Int]' has no member 'sortInPlace'
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'
```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
var l = l
var l2 = l
var l3 = l
var l4 = l
var l5 = l
var l6 = l
var l7 = l
var l8 = l
var l9 = l
var l10 = l
var l11 = l
var l12 = l
var l13 = l
var l14 = l
var l15 = l
var l16 = l
var l17 = l
var l18 = l
var l19 = l
var l20 = l
var l21 = l
var l22 = l
var l23 = l
var l24 = l
var l25 = l
var l26 = l
var l27 = l
var l28 = l
var l29 = l
var l30 = l
var l31 = l
var l32 = l
var l33 = l
var l34 = l
var l35 = l
var l36 = l
var l37 = l
var l38 = l
var l39 = l
var l40 = l
var l41 = l
var l42 = l
var l43 = l
var l44 = l
var l45 = l
var l46 = l
var l47 = l
var l48 = l
var l49 = l
var l50 = l
var l51 = l
var l52 = l
var l53 = l
var l54 = l
var l55 = l
var l56 = l
var l57 = l
var l58 = l
var l59 = l
var l60 = l
var l61 = l
var l62 = l
var l63 = l
var l64 = l
var l65 = l
var l66 = l
var l67 = l
var l68 = l
var l69 = l
var l70 = l
var l71 = l
var l72 = l
var l73 = l
var l74 = l
var l75 = l
var l76 = l
var l77 = l
var l78 = l
var l79 = l
var l80 = l
var l81 = l
var l82 = l
var l83 = l
var l84 = l
var l85 = l
var l86 = l
var l87 = l
var l88 = l
var l89 = l
var l90 = l
var l91 = l
var l92 = l
var l93 = l
var l94 = l
var l95 = l
var l96 = l
var l97 = l
var l98 = l
var l99 = l
var l100 = l
var l101 = l
var l102 = l
var l103 = l
var l104 = l
var l105 = l
var l106 = l
var l107 = l
var l108 = l
var l109 = l
var l110 = l
var l111 = l
var l112 = l
var l113 = l
var l114 = l
var l115 = l
var l116 = l
var l117 = l
var l118 = l
var l119 = l
var l120 = l
var l121 = l
var l122 = l
var l123 = l
var l124 = l
var l125 = l
XCTAssertTrue(median(l: [3, 1, 2, 4, 5]) == 3) // cannot find 'median' in scope
XCTAssertTrue(median(l: [-10, 4, 6, 1000, 10, 20]) == 8.0) // cannot find 'median' in scope
XCTAssertTrue(median(l: [5]) == 5) // cannot find 'median' in scope
XCTAssertTrue(median(l: [6, 5]) == 5.5) // cannot find 'median' in scope
XCTAssertTrue(median(l: [8, 1, 3, 9, 9, 2, 7]) == 7) // cannot find 'median' in scope
func median(l: [Int]) -> Double {
var l = l
l.sort()
let n = l.count
return n % 2 == 0 ? (Double(l[n / 2 - 1]) + Double(l[n / 2])) / 2 : Double(l[n / 2])
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
var l = l
l.sort()
let n = l.count
return n % 2 == 0 ? (Double(l[n / 2 - 1]) + Double(l[n / 2])) / 2 : Double(l[n / 2])
}
```
func median(l: [Int]) -> Double {
// TODO: Implement this function
return 0
}
```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
return 0
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
// TODO: Implement this function
return 0.0
}
```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
return 0.0
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
var l = l
l.sort()
let count = l.count
let index = count / 2
if count % 2 == 0 {
return Double(l[index-1] + l[index]) / 2.0
} else {
return Double(l[index])
}
}
```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 {
var l = l
l.sort()
let count = l.count
let index = count / 2
if count % 2 == 0 {
return Double(l[index-1] + l[index]) / 2.0
} else {
return Double(l[index])
}
}
```
func median(l: [Int]) -> Double {
var l = l
l.sort()
let count = l.count
let index = count / 2
if count % 2 == 0 {
return Double(l[index] + l[index - 1]) / 2
} else {
return Double(l[index])
}
}
```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 {
var l = l
l.sort()
let count = l.count
let index = count / 2
if count % 2 == 0 {
return Double(l[index] + l[index - 1]) / 2
} else {
return Double(l[index])
}
}
```
func isPalindrome(text: String) -> Bool {
let text = text.lowercased().filter { $0.isLetter }
return text.reversed() == text
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased().filter { $0.isLetter }
return text.reversed() == text
}
```
return text.reversed() == text // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'String'
func isPalindrome(text: String) -> Bool {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Bool'
func isPalindrome(text: String) -> Bool {
// TODO: Implement this function
}
```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 {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'Bool'
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
var i = 0
var j = text.count - 1
while i < j {
if text[text.index(text.startIndex, offsetBy: i)] != text[text.index(text.startIndex, offsetBy: j)] {
return false
}
i += 1
j -= 1
}
return true
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
var i = 0
var j = text.count - 1
while i < j {
if text[text.index(text.startIndex, offsetBy: i)] != text[text.index(text.startIndex, offsetBy: j)] {
return false
}
i += 1
j -= 1
}
return true
}
```
func isPalindrome(text: String) -> Bool {
// TODO: Implement this function
return false
}
```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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func isPalindrome(text: String) -> Bool {
// TODO: Implement this function
return false
}
```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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func isPalindrome(text: String) -> Bool {
let text = text.lowercased().replacingOccurrences(of: " ", with: "")
let textArray = Array(text)
for i in 0..<textArray.count/2 {
if textArray[i] != textArray[textArray.count - 1 - i] {
return false
}
}
return true
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased().replacingOccurrences(of: " ", with: "")
let textArray = Array(text)
for i in 0..<textArray.count/2 {
if textArray[i] != textArray[textArray.count - 1 - i] {
return false
}
}
return true
}
```
func isPalindrome(text: String) -> Bool {
let text = text.lowercased().replacingOccurrences(of: " ", with: "")
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().replacingOccurrences(of: " ", with: "")
let reversed = String(text.reversed())
return text == reversed
}
```
func isPalindrome(text: String) -> Bool {
let text = text.lowercased().replacingOccurrences(of: " ", with: "")
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().replacingOccurrences(of: " ", with: "")
let reversed = String(text.reversed())
return text == reversed
}
```
func isPalindrome(text: String) -> Bool {
// TODO: Implement this function
return false
}
```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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n != 0 {
if n & 1 != 0 {
result = (result * p) % p
}
p = (p * p) % p
n >>= 1
}
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 & 1 != 0 {
result = (result * p) % p
}
p = (p * p) % p
n >>= 1
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n, p = p, r = 1
while n > 0 {
if n % 2 == 1 {
r = (r * p) % p
}
p = (p * p) % p
n /= 2
}
return r
}
```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, p = p, r = 1
while n > 0 {
if n % 2 == 1 {
r = (r * p) % p
}
p = (p * p) % p
n /= 2
}
return r
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n, 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, 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 modp(n: Int, p: Int) -> Int {
var n = n, p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n = n >> 1
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, p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n = n >> 1
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 res = 1
while n > 0 {
if n % 2 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n = n >> 1
}
return res
}
```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 res = 1
while n > 0 {
if n % 2 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n = n >> 1
}
return res
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res: Int = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```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 res: Int = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res: Int = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```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 res: Int = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
var n = n, 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, 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 modp(n: Int, p: Int) -> Int {
var n = n, p = p, result = 1
while n > 0 {
if n & 1 == 1 {
result = (result * p) % p
}
p = (p * p) % p
n >>= 1
}
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, p = p, result = 1
while n > 0 {
if n & 1 == 1 {
result = (result * p) % p
}
p = (p * p) % p
n >>= 1
}
return result
}
```
// Fatal error: Division by zero in remainder operation
func removeVowels(text: String) -> String {
return text.filter {
!$0.isVowel
}
}
```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 {
return text.filter {
!$0.isVowel
}
}
```
return text.filter { // cannot convert return expression of type '[String.Element]' (aka 'Array<Character>') to return type 'String'
return text.filter { // trailing closure passed to parameter of type 'Predicate<String.Element>' (aka 'Predicate<Character>') that does not accept a closure
func removeVowels(text: String) -> String {
return text.filter { !$0.isVowel }
}
```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 {
return text.filter { !$0.isVowel }
}
```
return text.filter { !$0.isVowel } // cannot convert return expression of type '[String.Element]' (aka 'Array<Character>') to return type 'String'
return text.filter { !$0.isVowel } // trailing closure passed to parameter of type 'Predicate<String.Element>' (aka 'Predicate<Character>') that does not accept a closure
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let textArray = text.map { String($0) }
let filteredText = textArray.filter { !vowels.contains($0) }
return filteredText.joined()
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let textArray = text.map { String($0) }
let filteredText = textArray.filter { !vowels.contains($0) }
return filteredText.joined()
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if !["a", "e", "i", "o", "u"].contains(String(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 !["a", "e", "i", "o", "u"].contains(String(char)) {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
```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 {
return text.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char).lowercased()) {
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 {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char).lowercased()) {
result += String(char)
}
}
return result
}
```
func removeVowels(text: String) -> String {
return text.filter {
$0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u"
}
}
```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 {
return text.filter {
$0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u"
}
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
```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 {
return text.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
let charString = String(char)
if vowels.contains(charString) {
continue
} else {
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 vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
let charString = String(char)
if vowels.contains(charString) {
continue
} else {
result.append(char)
}
}
return result
}
```
var vowels = ["a", "e", "i", "o", "u"] // variable 'vowels' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var vowels = ["a","e","i","o","u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText.append(char)
}
}
return newText
}
```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 vowels = ["a","e","i","o","u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText.append(char)
}
}
return newText
}
```
var vowels = ["a","e","i","o","u"] // variable 'vowels' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
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 {
// TODO: Implement this function
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 {
// TODO: Implement this function
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for number in l {
if number >= 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 number in l {
if number >= t {
return false
}
}
return true
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
// your code here
if l.contains(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 {
// your code here
if l.contains(t) {
return false
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
let result = l.filter { $0 < t }
if result.count == l.count {
return true
}
return false
}
```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 {
let result = l.filter { $0 < t }
if result.count == l.count {
return true
}
return false
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
let result = l.filter { $0 < t }
if l == result {
return true
} else {
return false
}
}
```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 {
let result = l.filter { $0 < t }
if l == result {
return true
} else {
return false
}
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
// TODO: Write your code here.
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 {
// TODO: Write your code here.
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.allSatisfy { $0 < t }
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.allSatisfy { $0 < t }
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
var result = true
for i in l {
if i >= t {
result = false
break
}
}
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
break
}
}
return result
}
```
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 power(x: Int, y: Int) -> Int {
return x ^ y
}
func sqrt(x: Int) -> Int {
return x ^ 0.5
}
func abs(x: Int) -> Int {
return x
}
func factorial(x: Int) -> Int {
return x
}
func fibonacci(n: Int) -> Int {
return n
}
```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: 5, y: 3) == 2
// subtract(x: 10, y: 7) == 3
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: 10, y: 5) == 2
// divide(x: 14, y: 7) == 2
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Raise a number x to the power of y
// power(x: 2, y: 3) == 8
// power(x: 5, y: 2) == 25
func power(x: Int, y: Int) -> Int {
return x ^ y
}
// Take the square root of a number
// sqrt(x: 16) == 4
// sqrt(x: 25) == 5
func sqrt(x: Int) -> Int {
return x ^ 0.5
}
// Take the square root of a number
// sqrt(x: 16) == 4
// sqrt(x: 25) == 5
func sqrt(x: Int) -> Int {
return x ^ 0.5
}
// Calculate the absolute value of a number
// abs(x: -5) == 5
// abs(x: 3) == 3
func abs(x: Int) -> Int {
return x
}
// Calculate the factorial of a number
// factorial(x: 5) == 120
// factorial(x: 7) == 5040
func factorial(x: Int) -> Int {
return x
}
// Calculate the nth fibonacci number
// fibonacci(n: 0) == 0
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 3) == 2
// fibonacci(n: 4) == 3
// fibonacci(n: 5) == 5
// fibonacci(n: 6) == 8
// fibonacci(n: 7) == 13
// fibonacci(n: 8) == 21
// fibonacci(n: 9) == 34
// fibonacci(n: 10) == 55
func fibonacci(n: Int) -> Int {
return n
}
// Calculate the nth fibonacci number
// fibonacci(n: 0) == 0
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 3) == 2
// fibonacci(n: 4) == 3
// fibonacci(n: 5) == 5
// fibonacci(n: 6) == 8
// fibonacci(n: 7) == 13
// fibonacci(n: 8) == 21
// fibonacci(n: 9) == 34
// fibonacci(n: 10) == 55
func fibonacci(n: Int) -> Int {
return n
}
// Calculate the nth fibonacci number
// fibonacci(n: 0) == 0
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 3) == 2
// fibonacci(n: 4) == 3
// fibonacci(n: 5) == 5
// fibonacci(n: 6) == 8
// fibonacci(n: 7) == 13
// fibonacci(n: 8) == 21
// fibonacci(n: 9) == 34
// fibonacci(n: 10) == 55
func fibonacci(n: Int) -> Int {
return n
}
// Calculate the nth fibonacci number
// fibonacci(n: 0) == 0
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(
return x ^ 0.5 // cannot convert value of type 'Double' to expected argument type 'Int'
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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// Add two numbers x and y
// add(x: 2, y: 3) == 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 multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func subtract(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
}
// 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: 10, y: 5) == 2
// divide(x: 10, y: 2) == 5
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Subtract two numbers x and y
// subtract(x: 10, y: 5) == 5
// subtract(x: 10, y: 2) == 8
func subtract(x: Int, y: Int) -> Int {
return x - y
}
```
func add(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 subtract(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 absolute(x: Int) -> Int {
return x < 0 ? -x : x
}
func square(x: Int) -> Int {
return x * x
}
func cube(x: Int) -> Int {
return x * x * x
}
func nthPower(x: Int, n: Int) -> Int {
return Int(pow(Double(x), Double(n)))
}
func squareRoot(x: Int) -> Double {
return sqrt(Double(x))
}
func nthRoot(x: Int, n: Int) -> Double {
return pow(Double(x), 1.0 / Double(n))
}
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
func fibonacci(x: Int) -> [Int] {
var result = [0, 1]
for _ in 2...x {
let next = result[result.count - 1] + result[result.count - 2]
result.append(next)
}
return result
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 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: 10, y: 2) == 5
// divide(x: 10, y: 3) == 3
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Subtract two numbers x and y
// subtract(x: 10, y: 2) == 8
// subtract(x: 10, y: 3) == 7
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Calculate the remainder of x divided by y
// remainder(x: 10, y: 2) == 0
// remainder(x: 10, y: 3) == 1
func remainder(x: Int, y: Int) -> Int {
return x % y
}
// Calculate the average of two numbers x and y
// average(x: 10, y: 2) == 6
// average(x: 10, y: 3) == 6.5
func average(x: Int, y: Int) -> Double {
return Double(x + y) / 2
}
// Calculate the absolute value of a number x
// absolute(x: -10) == 10
// absolute(x: 10) == 10
func absolute(x: Int) -> Int {
return x < 0 ? -x : x
}
// Calculate the square of a number x
// square(x: 10) == 100
// square(x: 2) == 4
func square(x: Int) -> Int {
return x * x
}
// Calculate the cube of a number x
// cube(x: 10) == 1000
// cube(x: 2) == 8
func cube(x: Int) -> Int {
return x * x * x
}
// Calculate the nth power of a number x
// nthPower(x: 10, n: 2) == 100
// nthPower(x: 2, n: 3) == 8
func nthPower(x: Int, n: Int) -> Int {
return Int(pow(Double(x), Double(n)))
}
// Calculate the square root of a number x
// squareRoot(x: 100) == 10
// squareRoot(x: 4) == 2
func squareRoot(x: Int) -> Double {
return sqrt(Double(x))
}
// Calculate the nth root of a number x
// nthRoot(x: 100, n: 2) == 10
// nthRoot(x: 8, n: 3) == 2
func nthRoot(x: Int, n: Int) -> Double {
return pow(Double(x), 1.0 / Double(n))
}
// Calculate the factorial of a number x
// factorial(x: 5) == 120
// factorial(x: 3) == 6
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
// Calculate the fibonacci sequence of a number x
// fibonacci(x: 5) == [0, 1, 1, 2, 3]
// fibonacci(x: 3) == [0, 1, 1]
func fibonacci(x: Int) -> [Int] {
var result = [0, 1]
for _ in 2...x {
let next = result[result.count - 1] + result[result.count - 2]
result.append(next)
}
return result
}
// Calculate the sum of all numbers in an array
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([10, 20, 30, 40, 50])
func add(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 subtract(x: Int, y: Int) -> Int {
return x - y
}
func modulo(x: Int, y: Int) -> Int {
return x % y
}
func absolute(x: Int) -> Int {
return abs(x)
}
func square(x: Int) -> Int {
return x * x
}
func cube(x: Int) -> Int {
return x * x * x
}
func squareRoot(x: Int) -> Double {
return sqrt(Double(x))
}
func cubeRoot(x: Int) -> Double {
return pow(Double(x), 1/3)
}
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
func logarithm(x: Int, y: Int) -> Double {
return log(Double(x)) / log(Double(y))
}
func sine(x: Int) -> Double {
return sin(Double(x))
}
```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
}
// 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: 6, y: 3) == 2
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Subtract two numbers x and y
// subtract(x: 6, y: 3) == 3
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Calculate the remainder of x divided by y
// modulo(x: 6, y: 3) == 0
// modulo(x: 5, y: 7) == 5
func modulo(x: Int, y: Int) -> Int {
return x % y
}
// Calculate the absolute value of x
// absolute(x: 6) == 6
// absolute(x: -6) == 6
func absolute(x: Int) -> Int {
return abs(x)
}
// Calculate the square of x
// square(x: 6) == 36
// square(x: -6) == 36
func square(x: Int) -> Int {
return x * x
}
// Calculate the cube of x
// cube(x: 6) == 216
// cube(x: -6) == -216
func cube(x: Int) -> Int {
return x * x * x
}
// Calculate the square root of x
// squareRoot(x: 6) == 2.449489742783178
// squareRoot(x: -6) == 0
func squareRoot(x: Int) -> Double {
return sqrt(Double(x))
}
// Calculate the cube root of x
// cubeRoot(x: 6) == 1.8171205928321397
// cubeRoot(x: -6) == -1.8171205928321397
func cubeRoot(x: Int) -> Double {
return pow(Double(x), 1/3)
}
// Calculate the factorial of x
// factorial(x: 6) == 720
// factorial(x: 0) == 1
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
// Calculate the power of x raised to the y
// power(x: 6, y: 3) == 216
// power(x: 6, y: 0) == 1
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
// Calculate the logarithm of x to the base y
// logarithm(x: 6, y: 2) == 2.584962500721156
// logarithm(x: 6, y: 10) == 0.8450980392156862
func logarithm(x: Int, y: Int) -> Double {
return log(Double(x)) / log(Double(y))
}
// Calculate the sine of x
// sine(x: 6) == 0.9974949806773192
// sine(x: -6) == -0.9974949806773192
func sine(x: Int) -> Double {
return sin(Double(x))
}
// Calculate the cosine of x
// cosine(x: 6) == 0.06975647371134018
// cosine(x: -6) == -0.0697564
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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// Add two numbers x and y
// add(x: 2, y: 3) == 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// Add two numbers x and y
// add(x: 2, y: 3) == 5
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
if s0.count != s1.count {
return false
}
var count0 = [Character: Int]()
var count1 = [Character: Int]()
for c in s0 {
if let count = count0[c] {
count0[c] = count + 1
} else {
count0[c] = 1
}
}
for c in s1 {
if let count = count1[c] {
count1[c] = count + 1
} else {
count1[c] = 1
}
}
for (c, count) in count0 {
if count1[c] != count {
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 {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
if s0.count != s1.count {
return false
}
var count0 = [Character: Int]()
var count1 = [Character: Int]()
for c in s0 {
if let count = count0[c] {
count0[c] = count + 1
} else {
count0[c] = 1
}
}
for c in s1 {
if let count = count1[c] {
count1[c] = count + 1
} else {
count1[c] = 1
}
}
for (c, count) in count0 {
if count1[c] != count {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
let s0 = s0.characters
let s1 = s1.characters
var s0Count = [Character: Int]()
var s1Count = [Character: Int]()
for c in s0 {
s0Count[c] = (s0Count[c] ?? 0) + 1
}
for c in s1 {
s1Count[c] = (s1Count[c] ?? 0) + 1
}
return s0Count == s1Count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
let s0 = s0.characters
let s1 = s1.characters
var s0Count = [Character: Int]()
var s1Count = [Character: Int]()
for c in s0 {
s0Count[c] = (s0Count[c] ?? 0) + 1
}
for c in s1 {
s1Count[c] = (s1Count[c] ?? 0) + 1
}
return s0Count == s1Count
}
```
let s0 = s0.characters // 'characters' is unavailable: Please use String directly
let s1 = s1.characters // 'characters' is unavailable: Please use String directly
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
while s0.count > 0 && s1.count > 0 {
let s0Char = s0.removeFirst()
let s1Char = s1.removeFirst()
if s0Char == s1Char {
continue
} 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 s0 = s0
var s1 = s1
while s0.count > 0 && s1.count > 0 {
let s0Char = s0.removeFirst()
let s1Char = s1.removeFirst()
if s0Char == s1Char {
continue
} else {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
var i = 0
var j = 0
var k = 0
var l = 0
while i < s0.count && j < s1.count {
if s0[s0.startIndex.advancedBy(i)] == s1[s1.startIndex.advancedBy(j)] {
i += 1
j += 1
} else {
if s0[s0.startIndex.advancedBy(i)] < s1[s1.startIndex.advancedBy(j)] {
k += 1
i += 1
} else {
l += 1
j += 1
}
}
}
return k == l
}
```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 i = 0
var j = 0
var k = 0
var l = 0
while i < s0.count && j < s1.count {
if s0[s0.startIndex.advancedBy(i)] == s1[s1.startIndex.advancedBy(j)] {
i += 1
j += 1
} else {
if s0[s0.startIndex.advancedBy(i)] < s1[s1.startIndex.advancedBy(j)] {
k += 1
i += 1
} else {
l += 1
j += 1
}
}
}
return k == l
}
```
if s0[s0.startIndex.advancedBy(i)] == s1[s1.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
if s0[s0.startIndex.advancedBy(i)] == s1[s1.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
if s0[s0.startIndex.advancedBy(i)] < s1[s1.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
if s0[s0.startIndex.advancedBy(i)] < s1[s1.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
var s0Chars = [Character: Int]()
var s1Chars = [Character: Int]()
for char in s0 {
s0Chars[char, default: 0] += 1
}
for char in s1 {
s1Chars[char, default: 0] += 1
}
return s0Chars.keys.count == s1Chars.keys.count && s0Chars.keys.contains(where: { s1Chars[$0, default: 0] == s0Chars[$0, default: 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 {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
var s0Chars = [Character: Int]()
var s1Chars = [Character: Int]()
for char in s0 {
s0Chars[char, default: 0] += 1
}
for char in s1 {
s1Chars[char, default: 0] += 1
}
return s0Chars.keys.count == s1Chars.keys.count && s0Chars.keys.contains(where: { s1Chars[$0, default: 0] == s0Chars[$0, default: 0] })
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.sorted()
let s1 = s1.sorted()
return s0 == 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 {
let s0 = s0.sorted()
let s1 = s1.sorted()
return s0 == s1
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
let s0Count = s0.reduce(into: [:]) { $0[$1, default: 0] += 1 }
let s1Count = s1.reduce(into: [:]) { $0[$1, default: 0] += 1 }
return s0Count.keys.allSatisfy { s1Count[$0] == s0Count[$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 {
if s0.count != s1.count {
return false
}
let s0Count = s0.reduce(into: [:]) { $0[$1, default: 0] += 1 }
let s1Count = s1.reduce(into: [:]) { $0[$1, default: 0] += 1 }
return s0Count.keys.allSatisfy { s1Count[$0] == s0Count[$0] }
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.sorted()
let s1 = s1.sorted()
if s0.count != s1.count { return false }
for i in 0..<s0.count {
if s0[i] != s1[i] {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.sorted()
let s1 = s1.sorted()
if s0.count != s1.count { return false }
for i in 0..<s0.count {
if s0[i] != s1[i] {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
var s0Chars = [Character]()
for char in s0 {
s0Chars.append(char)
}
for char in s1 {
if let index = s0Chars.index(of: char) {
s0Chars.remove(at: index)
} 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 {
if s0.count != s1.count {
return false
}
var s0Chars = [Character]()
for char in s0 {
s0Chars.append(char)
}
for char in s1 {
if let index = s0Chars.index(of: char) {
s0Chars.remove(at: index)
} else {
return false
}
}
return true
}
```
if let index = s0Chars.index(of: char) { // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
for c in s0 {
if let index = s1.index(of: c) {
s1.remove(at: index)
} else {
return false
}
}
return 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
for c in s0 {
if let index = s1.index(of: c) {
s1.remove(at: index)
} else {
return false
}
}
return s1.isEmpty
}
```
var s0 = s0 // variable 's0' was never mutated; consider changing to 'let' constant
if let index = s1.index(of: c) { // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
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
}
return fib(n: n-1) + fib(n: n-2)
}
```
func fib(n: Int) -> Int {
guard n > 0 else { return 0 }
var a = 0
var b = 1
for _ in 0..<n {
(a, b) = (b, a + b)
}
return a
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
guard n > 0 else { return 0 }
var a = 0
var b = 1
for _ in 0..<n {
(a, b) = (b, a + b)
}
return a
}
```
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 {
var a = 0
var b = 1
for _ in 0..<n {
let tmp = a + b
a = b
b = tmp
}
return a
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let tmp = a + b
a = b
b = tmp
}
return a
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
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
}
if n == 2 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
var a = 0, b = 1, c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
var a = 0, b = 1, c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```
// XCTAssertTrue failed
func fib(n: Int) -> Int {
guard n > 0 else { return 0 }
if n <= 2 { return 1 }
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 {
guard n > 0 else { return 0 }
if n <= 2 { return 1 }
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
guard n > 0 else { return 0 }
guard n > 1 else { return 1 }
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 {
guard n > 0 else { return 0 }
guard n > 1 else { return 1 }
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
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
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
var a = 0, b = 1, c = 1
for _ in 2..<n {
(a, b, c) = (b, c, a + b)
}
return c
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
var a = 0, b = 1, c = 1
for _ in 2..<n {
(a, b, c) = (b, c, a + b)
}
return c
}
```
// XCTAssertTrue failed
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.popLast() == nil {
return false
}
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.popLast() == nil {
return false
}
}
}
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.popLast() == nil {
return false
}
}
}
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.popLast() == nil {
return false
}
}
}
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 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 bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
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 bracket == ">" {
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 bracket == ">" {
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 bracket == ">" {
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.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```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.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else {
if stack.popLast() != "<" {
return false
}
}
}
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.popLast() != "<" {
return false
}
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty {
return false
}
stack.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 bracket == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func monotonic(l: [Int]) -> Bool {
let sorted = l.sorted()
return l == sorted || l == sorted.reversed()
}
```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 {
let sorted = l.sorted()
return l == sorted || l == sorted.reversed()
}
```
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isIncreasing = false
}
if l[i] < l[i+1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```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 isIncreasing = true
var isDecreasing = true
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isIncreasing = false
}
if l[i] < l[i+1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isIncreasing = false
}
if l[i] < l[i+1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```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 isIncreasing = true
var isDecreasing = true
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isIncreasing = false
}
if l[i] < l[i+1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isIncreasing = false
}
if l[i] < l[i+1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```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 isIncreasing = true
var isDecreasing = true
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isIncreasing = false
}
if l[i] < l[i+1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
let sorted = l.sorted()
if sorted == l {
return true
} else if sorted.reversed() == l {
return true
}
return false
}
```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 {
let sorted = l.sorted()
if sorted == l {
return true
} else if sorted.reversed() == l {
return true
}
return false
}
```
func monotonic(l: [Int]) -> Bool {
if l.count < 2 { return true }
let isIncreasing = l.reduce(true) { $0 && ($1 >= $2) }
let isDecreasing = l.reduce(true) { $0 && ($1 <= $2) }
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count < 2 { return true }
let isIncreasing = l.reduce(true) { $0 && ($1 >= $2) }
let isDecreasing = l.reduce(true) { $0 && ($1 <= $2) }
return isIncreasing || isDecreasing
}
```
let isIncreasing = l.reduce(true) { $0 && ($1 >= $2) } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
let isDecreasing = 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 {
if l.count == 0 { return false }
if l.count == 1 { return true }
var isIncreasing = l[1] > l[0]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
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 {
if l.count == 0 { return false }
if l.count == 1 { return true }
var isIncreasing = l[1] > l[0]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
```
var isIncreasing = l[1] > l[0] // variable 'isIncreasing' was never mutated; consider changing to 'let' constant
func monotonic(l: [Int]) -> Bool {
let l = l.map { $0 }
if l.count < 2 {
return true
}
let isIncreasing = l[0] <= l[1]
for i in 1..<l.count {
if isIncreasing && l[i] < l[i-1] {
return false
}
if !isIncreasing && l[i] > l[i-1] {
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 {
let l = l.map { $0 }
if l.count < 2 {
return true
}
let isIncreasing = l[0] <= l[1]
for i in 1..<l.count {
if isIncreasing && l[i] < l[i-1] {
return false
}
if !isIncreasing && l[i] > l[i-1] {
return false
}
}
return true
}
```
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else {
return true
}
var isIncreasing = l[0] <= l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] > l[i - 1] {
continue
} else if l[i] == l[i - 1] {
continue
} else {
return false
}
} else {
if l[i] < l[i - 1] {
continue
} else if l[i] == l[i - 1] {
continue
} else {
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
}
var isIncreasing = l[0] <= l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] > l[i - 1] {
continue
} else if l[i] == l[i - 1] {
continue
} else {
return false
}
} else {
if l[i] < l[i - 1] {
continue
} else if l[i] == l[i - 1] {
continue
} else {
return false
}
}
}
return true
}
```
var isIncreasing = l[0] <= l[1] // variable 'isIncreasing' was never mutated; consider changing to 'let' constant
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i - 1] > l[i] {
isIncreasing = false
}
if l[i - 1] < l[i] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```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 isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i - 1] > l[i] {
isIncreasing = false
}
if l[i - 1] < l[i] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
// TODO: Implement this function.
}
```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] {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return '[Int]'
func common(l1: [Int], l2: [Int]) -> [Int] {
// TODO: Implement this function
}
```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] {
// TODO: Implement this function
}
```
} // missing return in global function expected to return '[Int]'
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.unique()
}
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
return l1.filter { l2.contains($0) && l3.contains($0) }.unique()
}
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
return l1.filter { l2.contains($0) && l3.contains($0) && l4.contains($0) }.unique()
}
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int], l5: [Int]) -> [Int] {
return l1.filter { l2.contains($0) && l3.contains($0) && l4.contains($0) && l5.contains($0) }.unique()
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.unique()
}
// Return sorted unique common elements for three arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [653, 1, 3, 5]) == [1, 5, 653]
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
return l1.filter { l2.contains($0) && l3.contains($0) }.unique()
}
// Return sorted unique common elements for four arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [653, 1, 3, 5], l4: [1, 5, 653, 121]) == [1, 5, 653]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
return l1.filter { l2.contains($0) && l3.contains($0) && l4.contains($0) }.unique()
}
// Return sorted unique common elements for five arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [653, 1, 3, 5], l4: [1, 5, 653, 121], l5: [653, 1, 3, 5, 121]) == [1, 5, 653]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int], l5: [Int]) -> [Int] {
return l1.filter { l2.contains($0) && l3.contains($0) && l4.contains($0) && l5.contains($0) }.unique()
}
```
return l1.filter { l2.contains($0) }.unique() // value of type '[Int]' has no member 'unique'
return l1.filter { l2.contains($0) && l3.contains($0) }.unique() // value of type '[Int]' has no member 'unique'
return l1.filter { l2.contains($0) && l3.contains($0) && l4.contains($0) }.unique() // value of type '[Int]' has no member 'unique'
return l1.filter { l2.contains($0) && l3.contains($0) && l4.contains($0) && l5.contains($0) }.unique() // value of type '[Int]' has no member 'unique'
func common(l1: [Int], l2: [Int]) -> [Int] {
// TODO: Implement this function.
}
```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] {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return '[Int]'
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.unique()
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.unique()
}
```
return l1.filter { l2.contains($0) }.unique() // value of type '[Int]' has no member 'unique'
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var common = [Int]()
while !l1.isEmpty && !l2.isEmpty {
let l1Value = l1.remove(at: 0)
let l2Value = l2.remove(at: 0)
if l1Value == l2Value {
common.append(l1Value)
}
else if l1Value < l2Value {
l1.append(l1Value)
}
else {
l2.append(l2Value)
}
}
return common
}
```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 l1 = l1
var l2 = l2
var common = [Int]()
while !l1.isEmpty && !l2.isEmpty {
let l1Value = l1.remove(at: 0)
let l2Value = l2.remove(at: 0)
if l1Value == l2Value {
common.append(l1Value)
}
else if l1Value < l2Value {
l1.append(l1Value)
}
else {
l2.append(l2Value)
}
}
return common
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result: [Int] = []
while i < l1.count && j < l2.count {
if l1[i] < l2[j] {
i += 1
} else if l1[i] > l2[j] {
j += 1
} else {
result.append(l1[i])
i += 1
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result: [Int] = []
while i < l1.count && j < l2.count {
if l1[i] < l2[j] {
i += 1
} else if l1[i] > l2[j] {
j += 1
} else {
result.append(l1[i])
i += 1
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
// TODO: Implement this function
let l1 = l1.sorted()
let l2 = l2.sorted()
var result: [Int] = []
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] < l2[j] {
i += 1
} else if l1[i] > l2[j] {
j += 1
} else {
result.append(l1[i])
i += 1
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
// TODO: Implement this function
let l1 = l1.sorted()
let l2 = l2.sorted()
var result: [Int] = []
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] < l2[j] {
i += 1
} else if l1[i] > l2[j] {
j += 1
} else {
result.append(l1[i])
i += 1
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
// TODO: Implement this function.
var l1 = l1
var l2 = l2
var common = [Int]()
while l1.count != 0 && l2.count != 0 {
if l1[0] < l2[0] {
l1.remove(at: 0)
} else if l1[0] > l2[0] {
l2.remove(at: 0)
} else {
if !common.contains(l1[0]) {
common.append(l1[0])
}
l1.remove(at: 0)
l2.remove(at: 0)
}
}
return common
}
```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] {
// TODO: Implement this function.
var l1 = l1
var l2 = l2
var common = [Int]()
while l1.count != 0 && l2.count != 0 {
if l1[0] < l2[0] {
l1.remove(at: 0)
} else if l1[0] > l2[0] {
l2.remove(at: 0)
} else {
if !common.contains(l1[0]) {
common.append(l1[0])
}
l1.remove(at: 0)
l2.remove(at: 0)
}
}
return common
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var result = [Int]()
var i1 = 0
var i2 = 0
while i1 < l1.count && i2 < l2.count {
if l1[i1] == l2[i2] {
result.append(l1[i1])
i1 += 1
i2 += 1
} else if l1[i1] > l2[i2] {
i2 += 1
} else {
i1 += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var result = [Int]()
var i1 = 0
var i2 = 0
while i1 < l1.count && i2 < l2.count {
if l1[i1] == l2[i2] {
result.append(l1[i1])
i1 += 1
i2 += 1
} else if l1[i1] > l2[i2] {
i2 += 1
} else {
i1 += 1
}
}
return result
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrimeFactor = 1
for var i = 2; i <= n; i += 1 {
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 var i = 2; i <= n; i += 1 {
while n % i == 0 {
largestPrimeFactor = i
n /= i
}
}
return largestPrimeFactor
}
```
for var i = 2; i <= n; i += 1 { // C-style for statement has been removed in Swift 3
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrime = 1
var i = 2
while i <= n {
if n % i == 0 {
largestPrime = i
n = n / i
} else {
i = i + 1
}
}
return largestPrime
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var largestPrime = 1
var i = 2
while i <= n {
if n % i == 0 {
largestPrime = i
n = n / i
} else {
i = i + 1
}
}
return largestPrime
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var factor = 2
while n % factor != 0 {
factor += 1
}
n /= factor
while n > 1 {
if n % factor == 0 {
n /= factor
} else {
factor += 1
while n % factor != 0 {
factor += 1
}
n /= factor
}
}
return factor
}
```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 factor = 2
while n % factor != 0 {
factor += 1
}
n /= factor
while n > 1 {
if n % factor == 0 {
n /= factor
} else {
factor += 1
while n % factor != 0 {
factor += 1
}
n /= factor
}
}
return factor
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var factor = 2
while factor * factor <= n {
if n % factor == 0 {
n /= factor
} else {
factor += 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 factor = 2
while factor * factor <= n {
if n % factor == 0 {
n /= factor
} else {
factor += 1
}
}
return n
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var factor = 2
while n > 1 {
if n % factor == 0 {
n = n / factor
} else {
factor += 1
}
}
return factor
}
```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 factor = 2
while n > 1 {
if n % factor == 0 {
n = n / factor
} else {
factor += 1
}
}
return factor
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var primeFactor = 2
while n % 2 == 0 {
n /= 2
}
while primeFactor <= n {
if n % primeFactor == 0 {
n /= primeFactor
} else {
primeFactor += 1
}
}
return primeFactor
}
```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 primeFactor = 2
while n % 2 == 0 {
n /= 2
}
while primeFactor <= n {
if n % primeFactor == 0 {
n /= primeFactor
} else {
primeFactor += 1
}
}
return primeFactor
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var divisor = 2
while divisor * divisor <= n {
if n % divisor == 0 {
n /= divisor
} else {
divisor += 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 divisor = 2
while divisor * divisor <= n {
if n % divisor == 0 {
n /= divisor
} else {
divisor += 1
}
}
return n
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var divisor = 2
while divisor * divisor <= n {
while n % divisor == 0 {
n /= divisor
}
divisor += 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 divisor = 2
while divisor * divisor <= n {
while n % divisor == 0 {
n /= divisor
}
divisor += 1
}
return n
}
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var n = n
var primeFactors = [Int]()
var divisor = 2
while n > 1 {
if n % divisor == 0 {
primeFactors.append(divisor)
n /= divisor
} else {
divisor += 1
}
}
return primeFactors.last!
}
```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 primeFactors = [Int]()
var divisor = 2
while n > 1 {
if n % divisor == 0 {
primeFactors.append(divisor)
n /= divisor
} else {
divisor += 1
}
}
return primeFactors.last!
}
```
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
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 {
if n % i == 0 {
n = n / i
} else {
i = i + 1
}
}
return n
}
```
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 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.count == 0 {
return false
} else {
stack.removeLast()
}
}
}
return stack.count == 0
}
```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.count == 0 {
return false
} else {
stack.removeLast()
}
}
}
return stack.count == 0
}
```
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 bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
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 bracket == ")" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty {
return false
}
_ = stack.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 bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty {
return false
}
_ = stack.popLast()
}
}
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 bracket == ")" {
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 bracket == ")" {
if stack.isEmpty {
return false
} else {
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
} 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 char == ")" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
func derivative(xs: [Int]) -> [Int] {
// TODO: Implement this method
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] {
// TODO: Implement this method
return []
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
// TODO: your code here
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * i)
}
return result.filter{$0 != 0}
}
```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: your code here
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * i)
}
return result.filter{$0 != 0}
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
return xs.enumerated().map { $0.offset == 0 ? 0 : $0.offset * $0.element }
}
```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 xs.enumerated().map { $0.offset == 0 ? 0 : $0.offset * $0.element }
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
return xs.enumerated().filter { $0.offset != 0 }.map { $0.element * $0.offset }
}
```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 xs.enumerated().filter { $0.offset != 0 }.map { $0.element * $0.offset }
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i > 0 {
result.append(i * xs[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(i * xs[i])
}
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
return xs.enumerated().compactMap { (offset, value) in
offset == 0 ? nil : value * offset
}
}
```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 xs.enumerated().compactMap { (offset, value) in
offset == 0 ? nil : value * offset
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for (index, value) in xs.enumerated() {
if index != 0 {
result.append(value * index)
}
}
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 (index, value) in xs.enumerated() {
if index != 0 {
result.append(value * index)
}
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i > 0 {
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] * i)
}
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
result.append(0)
} 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(0)
} else {
result.append(xs[i] * i)
}
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
return xs.enumerated().compactMap { (index, value) -> Int? in
if index == 0 {
return nil
} else {
return value * index
}
}
}
```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 xs.enumerated().compactMap { (index, value) -> Int? in
if index == 0 {
return nil
} else {
return value * index
}
}
}
```
func fibfib(n: Int) -> Int {
var fibfibs = [0, 0, 1]
for i in 3...n {
fibfibs.append(fibfibs[i-1] + fibfibs[i-2] + fibfibs[i-3])
}
return fibfibs[n]
}
```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 fibfibs = [0, 0, 1]
for i in 3...n {
fibfibs.append(fibfibs[i-1] + fibfibs[i-2] + fibfibs[i-3])
}
return fibfibs[n]
}
```
// Fatal error: Range requires lowerBound <= upperBound
func fibfib(n: Int) -> Int {
if n < 3 {
return n
}
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 {
if n < 3 {
return n
}
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 {
var fib = [Int](repeating: 0, count: n+1)
fib[1] = 0
fib[2] = 1
for i in 3...n {
fib[i] = fib[i-1] + fib[i-2] + fib[i-3]
}
return fib[n]
}
```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 fib = [Int](repeating: 0, count: n+1)
fib[1] = 0
fib[2] = 1
for i in 3...n {
fib[i] = fib[i-1] + fib[i-2] + fib[i-3]
}
return fib[n]
}
```
// Fatal error: Range requires lowerBound <= upperBound
func fibfib(n: Int) -> Int {
var fibfibs = [0, 0, 1]
for i in 3...n {
fibfibs.append(fibfibs[i - 1] + fibfibs[i - 2] + fibfibs[i - 3])
}
return fibfibs[n]
}
```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 fibfibs = [0, 0, 1]
for i in 3...n {
fibfibs.append(fibfibs[i - 1] + fibfibs[i - 2] + fibfibs[i - 3])
}
return fibfibs[n]
}
```
// Fatal error: Range requires lowerBound <= upperBound
func fibfib(n: Int) -> Int {
if n < 3 {
return 0
} else if n == 3 {
return 1
} else {
var fibfibs = [0,0,1]
for _ in 3...n {
let newFibfib = fibfibs[fibfibs.count - 1] + fibfibs[fibfibs.count - 2] + fibfibs[fibfibs.count - 3]
fibfibs.append(newFibfib)
}
return fibfibs[n]
}
}
```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
} else if n == 3 {
return 1
} else {
var fibfibs = [0,0,1]
for _ in 3...n {
let newFibfib = fibfibs[fibfibs.count - 1] + fibfibs[fibfibs.count - 2] + fibfibs[fibfibs.count - 3]
fibfibs.append(newFibfib)
}
return fibfibs[n]
}
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b + c
b = c + a
c = a + b
}
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 + c
b = c + a
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var fib = [Int]()
fib.append(0)
fib.append(0)
fib.append(1)
if n < 3 {
return fib[n]
}
for i in 3...n {
fib.append(fib[i - 1] + fib[i - 2] + fib[i - 3])
}
return fib[n]
}
```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 fib = [Int]()
fib.append(0)
fib.append(0)
fib.append(1)
if n < 3 {
return fib[n]
}
for i in 3...n {
fib.append(fib[i - 1] + fib[i - 2] + fib[i - 3])
}
return fib[n]
}
```
func fibfib(n: Int) -> Int {
var fibFib = [Int](repeating: 0, count: n + 1)
fibFib[1] = 0
fibFib[2] = 0
fibFib[3] = 1
for i in 4...n {
fibFib[i] = fibFib[i - 1] + fibFib[i - 2] + fibFib[i - 3]
}
return fibFib[n]
}
```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 fibFib = [Int](repeating: 0, count: n + 1)
fibFib[1] = 0
fibFib[2] = 0
fibFib[3] = 1
for i in 4...n {
fibFib[i] = fibFib[i - 1] + fibFib[i - 2] + fibFib[i - 3]
}
return fibFib[n]
}
```
// Fatal error: Index out of range
func fibfib(n: Int) -> Int {
var fib = [0, 0, 1]
for i in 3...n {
fib.append(fib[i - 1] + fib[i - 2] + fib[i - 3])
}
return fib[n]
}
```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 fib = [0, 0, 1]
for i in 3...n {
fib.append(fib[i - 1] + fib[i - 2] + fib[i - 3])
}
return fib[n]
}
```
// Fatal error: Range requires lowerBound <= upperBound
func fibfib(n: Int) -> Int {
var fibFib = [Int]()
fibFib.append(0)
fibFib.append(0)
fibFib.append(1)
for i in 3...n {
fibFib.append(fibFib[i - 1] + fibFib[i - 2] + fibFib[i - 3])
}
return fibFib[n]
}
```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 fibFib = [Int]()
fibFib.append(0)
fibFib.append(0)
fibFib.append(1)
for i in 3...n {
fibFib.append(fibFib[i - 1] + fibFib[i - 2] + fibFib[i - 3])
}
return fibFib[n]
}
```
// Fatal error: Range requires lowerBound <= upperBound
func vowelsCount(s: String) -> Int {
var count = 0
let vowels = ["a", "e", "i", "o", "u"]
for char in s {
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 {
var count = 0
let vowels = ["a", "e", "i", "o", "u"]
for char in s {
if vowels.contains(String(char)) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
let vowels = ["a", "e", "i", "o", "u"]
let lastLetter = s.last!
var count = 0
for letter in s {
if vowels.contains(String(letter)) {
count += 1
}
}
if lastLetter == "y" {
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"]
let lastLetter = s.last!
var count = 0
for letter in s {
if vowels.contains(String(letter)) {
count += 1
}
}
if lastLetter == "y" {
count -= 1
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
let vowels = ["a", "e", "i", "o", "u", "y"]
let s = s.lowercased()
for i in s {
if vowels.contains(String(i)) {
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
let vowels = ["a", "e", "i", "o", "u", "y"]
let s = s.lowercased()
for i in s {
if vowels.contains(String(i)) {
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 {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
let vowels = ["a", "e", "i", "o", "u"]
let lastLetter = s.last
if vowels.contains(lastLetter!) {
return s.count - 1
} else {
return s.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"]
let lastLetter = s.last
if vowels.contains(lastLetter!) {
return s.count - 1
} else {
return s.count
}
}
```
if vowels.contains(lastLetter!) { // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
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.lowercased() {
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.lowercased() {
switch char {
case "a", "e", "i", "o", "u":
count += 1
default:
break
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
let vowels = ["a", "e", "i", "o", "u"]
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 {
var count = 0
let vowels = ["a", "e", "i", "o", "u"]
for char in s.lowercased() {
if vowels.contains(String(char)) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
let vowels = ["a", "e", "i", "o", "u"]
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 {
var count = 0
let vowels = ["a", "e", "i", "o", "u"]
for char in s.lowercased() {
if vowels.contains(String(char)) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var x = x, shift = shift
let digits = String(x).characters
if shift > digits.count {
shift %= digits.count
}
if shift == 0 {
return String(x)
}
var result = digits.dropLast(digits.count - shift)
result.append(contentsOf: digits.prefix(digits.count - shift))
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var x = x, shift = shift
let digits = String(x).characters
if shift > digits.count {
shift %= digits.count
}
if shift == 0 {
return String(x)
}
var result = digits.dropLast(digits.count - shift)
result.append(contentsOf: digits.prefix(digits.count - shift))
return String(result)
}
```
let digits = String(x).characters // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shift = shift % digits.count
if shift == 0 { return String(digits) }
let (head, tail) = digits.split(at: digits.count - shift)
return tail + head
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shift = shift % digits.count
if shift == 0 { return String(digits) }
let (head, tail) = digits.split(at: digits.count - shift)
return tail + head
}
```
if shift == 0 { return String(digits) } // no exact matches in call to initializer
let (head, tail) = digits.split(at: digits.count - shift) // cannot convert value of type '[ArraySlice<Int>]' to specified type '(_, _)'
let (head, tail) = digits.split(at: digits.count - shift) // no exact matches in call to instance method 'split'
func circularShift(x: Int, shift: Int) -> String {
var x = x, shift = shift
let digits = String(x).map { String($0) }
if shift > digits.count {
shift = digits.count
x = 0
}
let shiftDigits = Array(digits.dropFirst(digits.count - shift))
let unshiftDigits = Array(digits.dropLast(shift))
let result = unshiftDigits + shiftDigits
return result.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 {
var x = x, shift = shift
let digits = String(x).map { String($0) }
if shift > digits.count {
shift = digits.count
x = 0
}
let shiftDigits = Array(digits.dropFirst(digits.count - shift))
let unshiftDigits = Array(digits.dropLast(shift))
let result = unshiftDigits + shiftDigits
return result.joined()
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var x = x, shift = shift
var digits = [Int]()
if shift > String(x).characters.count {
while x > 0 {
digits.append(x % 10)
x /= 10
}
return digits.reverse().map{ String($0) }.joinWithSeparator("")
}
while x > 0 {
digits.append(x % 10)
x /= 10
}
for _ in 0..<shift {
let last = digits.removeLast()
digits.insert(last, atIndex: 0)
}
return digits.map{ String($0) }.joinWithSeparator("")
}
```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 {
var x = x, shift = shift
var digits = [Int]()
if shift > String(x).characters.count {
while x > 0 {
digits.append(x % 10)
x /= 10
}
return digits.reverse().map{ String($0) }.joinWithSeparator("")
}
while x > 0 {
digits.append(x % 10)
x /= 10
}
for _ in 0..<shift {
let last = digits.removeLast()
digits.insert(last, atIndex: 0)
}
return digits.map{ String($0) }.joinWithSeparator("")
}
```
if shift > String(x).characters.count { // 'characters' is unavailable: Please use String directly
return digits.reverse().map{ String($0) }.joinWithSeparator("") // value of tuple type '()' has no member 'map'
digits.insert(last, atIndex: 0) // no exact matches in call to instance method 'insert'
return digits.map{ String($0) }.joinWithSeparator("") // value of type '[String]' has no member 'joinWithSeparator'
func circularShift(x: Int, shift: Int) -> String {
var digits = String(x).characters
let count = digits.count
if shift > count {
return String(digits.reverse())
}
var result = digits.suffix(count - shift) + digits.prefix(shift)
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = String(x).characters
let count = digits.count
if shift > count {
return String(digits.reverse())
}
var result = digits.suffix(count - shift) + digits.prefix(shift)
return String(result)
}
```
var digits = String(x).characters // 'characters' is unavailable: Please use String directly
return String(digits.reverse()) // value of type 'String' has no member 'reverse'
func circularShift(x: Int, shift: Int) -> String {
var digits = String(x).characters
var result = ""
if shift >= digits.count {
// Reverse digits
for i in stride(from: digits.count - 1, through: 0, by: -1) {
result += String(digits[digits.index(digits.startIndex, offsetBy: i)])
}
} else {
// Circular shift
let shiftIndex = digits.index(digits.startIndex, offsetBy: shift)
let firstPart = digits.prefix(upTo: shiftIndex)
let secondPart = digits.suffix(from: shiftIndex)
for i in secondPart {
result += String(i)
}
for i in firstPart {
result += String(i)
}
}
return result
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = String(x).characters
var result = ""
if shift >= digits.count {
// Reverse digits
for i in stride(from: digits.count - 1, through: 0, by: -1) {
result += String(digits[digits.index(digits.startIndex, offsetBy: i)])
}
} else {
// Circular shift
let shiftIndex = digits.index(digits.startIndex, offsetBy: shift)
let firstPart = digits.prefix(upTo: shiftIndex)
let secondPart = digits.suffix(from: shiftIndex)
for i in secondPart {
result += String(i)
}
for i in firstPart {
result += String(i)
}
}
return result
}
```
var digits = String(x).characters // 'characters' is unavailable: Please use String directly
var digits = String(x).characters // variable 'digits' was never mutated; consider changing to 'let' constant
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let shift = shift % digits.count
if shift == 0 { return String(digits) }
let first = digits[0 ..< digits.count - shift]
let second = digits[digits.count - shift ..< digits.count]
let result = second + first
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let shift = shift % digits.count
if shift == 0 { return String(digits) }
let first = digits[0 ..< digits.count - shift]
let second = digits[digits.count - shift ..< digits.count]
let result = second + first
return String(result)
}
```
let digits = String(x).characters.map { Int(String($0))! } // 'characters' is unavailable: Please use String directly
if shift == 0 { return String(digits) } // no exact matches in call to initializer
return String(result) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
var digits = String(x).map { Int(String($0))! }
if shift >= digits.count {
digits = digits.reversed()
} else {
digits = Array(digits[shift..<digits.count]) + Array(digits[0..<shift])
}
return digits.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 {
var digits = String(x).map { Int(String($0))! }
if shift >= digits.count {
digits = digits.reversed()
} else {
digits = Array(digits[shift..<digits.count]) + Array(digits[0..<shift])
}
return digits.map { String($0) }.joined()
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
if digits.count <= shift {
return digits.reversed().joined()
}
let head = digits.suffix(shift)
let tail = digits.prefix(digits.count - shift)
return (head + tail).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) }
if digits.count <= shift {
return digits.reversed().joined()
}
let head = digits.suffix(shift)
let tail = digits.prefix(digits.count - shift)
return (head + tail).joined()
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var x = x, shift = shift, result = ""
var digits = [Int]()
while x != 0 {
digits.append(x % 10)
x /= 10
}
while shift > digits.count {
shift -= digits.count
}
for i in 0 ..< digits.count - shift {
result += "\(digits[i])"
}
for i in digits.count - shift ..< digits.count {
result += "\(digits[i])"
}
return result
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var x = x, shift = shift, result = ""
var digits = [Int]()
while x != 0 {
digits.append(x % 10)
x /= 10
}
while shift > digits.count {
shift -= digits.count
}
for i in 0 ..< digits.count - shift {
result += "\(digits[i])"
}
for i in digits.count - shift ..< digits.count {
result += "\(digits[i])"
}
return result
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
return s.unicodeScalars.reduce(0) {
$0 + (CharacterSet.uppercaseLetters.contains($1) ? $1.value : 0)
}
}
```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 {
return s.unicodeScalars.reduce(0) {
$0 + (CharacterSet.uppercaseLetters.contains($1) ? $1.value : 0)
}
}
```
return s.unicodeScalars.reduce(0) { // cannot convert return expression of type 'UInt32' to return type 'Int'
func digitSum(s: String) -> Int {
let upperCase = s.uppercased()
var sum = 0
for char in upperCase {
if char.isLetter {
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 {
let upperCase = s.uppercased()
var sum = 0
for char in upperCase {
if char.isLetter {
sum += Int(char.asciiValue!)
}
}
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 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 {
let upperCase = s.uppercased()
var sum = 0
for char in upperCase {
if char.isLetter {
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 {
let upperCase = s.uppercased()
var sum = 0
for char in upperCase {
if char.isLetter {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLetter {
sum += Int(String(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.isLetter {
sum += Int(String(char).unicodeScalars.first!.value)
}
}
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 digitSum(s: String) -> Int {
let upperCaseLetters = s.uppercased()
var sum = 0
for char in upperCaseLetters {
if char.isLetter {
let asciiValue = Int(char.asciiValue!)
sum += 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 {
let upperCaseLetters = s.uppercased()
var sum = 0
for char in upperCaseLetters {
if char.isLetter {
let asciiValue = Int(char.asciiValue!)
sum += asciiValue
}
}
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 digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLetter && 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.isLetter && char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ")
let apples = Int(arr[0]) ?? 0
let oranges = Int(arr[2]) ?? 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 arr = s.split(separator: " ")
let apples = Int(arr[0]) ?? 0
let oranges = Int(arr[2]) ?? 0
let mango = n - apples - oranges
return mango
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ")
let apples = Int(fruits[0]) ?? 0
let oranges = Int(fruits[2]) ?? 0
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.components(separatedBy: " ")
let apples = Int(fruits[0]) ?? 0
let oranges = Int(fruits[2]) ?? 0
let mangoes = n - apples - oranges
return mangoes
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let s = s.components(separatedBy: " ")
let apples = Int(s[0]) ?? 0
let oranges = Int(s[2]) ?? 0
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 s = s.components(separatedBy: " ")
let apples = Int(s[0]) ?? 0
let oranges = Int(s[2]) ?? 0
let mangoes = n - (apples + oranges)
return mangoes
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
return n - apples - oranges
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let split = s.split(separator: " ")
let apples = Int(split[0])!
let oranges = Int(split[2])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let split = s.split(separator: " ")
let apples = Int(split[0])!
let oranges = Int(split[2])!
return n - apples - oranges
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " ")[0]) ?? 0
let oranges = Int(s.split(separator: " ")[2]) ?? 0
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 apples = Int(s.split(separator: " ")[0]) ?? 0
let oranges = Int(s.split(separator: " ")[2]) ?? 0
let mangoes = n - apples - oranges
return mangoes
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0]) ?? 0
let oranges = Int(arr[2]) ?? 0
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0]) ?? 0
let oranges = Int(arr[2]) ?? 0
return n - apples - oranges
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ")
let apples = Int(fruits[0].dropLast()) ?? 0
let oranges = Int(fruits[2].dropLast()) ?? 0
return n - (apples + oranges)
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ")
let apples = Int(fruits[0].dropLast()) ?? 0
let oranges = Int(fruits[2].dropLast()) ?? 0
return n - (apples + oranges)
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
let mango = n - (apples + oranges)
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
let mango = n - (apples + oranges)
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ").map(String.init)
let apples = Int(arr[0]) ?? 0
let oranges = Int(arr[3]) ?? 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 arr = s.split(separator: " ").map(String.init)
let apples = Int(arr[0]) ?? 0
let oranges = Int(arr[3]) ?? 0
let mango = n - apples - oranges
return mango
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue: Int?
var smallestEvenValueIndex: Int?
for (index, value) in arr.enumerated() {
if value % 2 == 0 && (smallestEvenValue == nil || value < smallestEvenValue!) {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
if let smallestEvenValue = smallestEvenValue, let smallestEvenValueIndex = smallestEvenValueIndex {
return [smallestEvenValue, smallestEvenValueIndex]
} else {
return []
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue: Int?
var smallestEvenValueIndex: Int?
for (index, value) in arr.enumerated() {
if value % 2 == 0 && (smallestEvenValue == nil || value < smallestEvenValue!) {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
if let smallestEvenValue = smallestEvenValue, let smallestEvenValueIndex = smallestEvenValueIndex {
return [smallestEvenValue, smallestEvenValueIndex]
} else {
return []
}
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEven = 0
var smallestIndex = 0
var smallestEvenIndex = 0
var smallestEvenValue = 0
var smallestValue = 0
var smallestValueIndex = 0
var smallestValueValue = 0
if arr.isEmpty {
return []
}
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if smallestEven == 0 {
smallestEven = value
smallestEvenIndex = index
smallestEvenValue = value
} else if value < smallestEven {
smallestEven = value
smallestEvenIndex = index
smallestEvenValue = value
} else if value == smallestEven {
smallestEven = value
smallestEvenIndex = index
smallestEvenValue = value
}
}
if smallestValue == 0 {
smallestValue = value
smallestValueIndex = index
smallestValueValue = value
} else if value < smallestValue {
smallestValue = value
smallestValueIndex = index
smallestValueValue = value
} else if value == smallestValue {
smallestValue = value
smallestValueIndex = index
smallestValueValue = value
}
}
if smallestEvenValue == smallestValueValue {
return [smallestEvenValue, smallestEvenIndex]
} else {
return [smallestValueValue, smallestValueIndex]
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = 0
var smallestIndex = 0
var smallestEvenIndex = 0
var smallestEvenValue = 0
var smallestValue = 0
var smallestValueIndex = 0
var smallestValueValue = 0
if arr.isEmpty {
return []
}
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if smallestEven == 0 {
smallestEven = value
smallestEvenIndex = index
smallestEvenValue = value
} else if value < smallestEven {
smallestEven = value
smallestEvenIndex = index
smallestEvenValue = value
} else if value == smallestEven {
smallestEven = value
smallestEvenIndex = index
smallestEvenValue = value
}
}
if smallestValue == 0 {
smallestValue = value
smallestValueIndex = index
smallestValueValue = value
} else if value < smallestValue {
smallestValue = value
smallestValueIndex = index
smallestValueValue = value
} else if value == smallestValue {
smallestValue = value
smallestValueIndex = index
smallestValueValue = value
}
}
if smallestEvenValue == smallestValueValue {
return [smallestEvenValue, smallestEvenIndex]
} else {
return [smallestValueValue, smallestValueIndex]
}
}
```
var smallestIndex = 0 // initialization of variable 'smallestIndex' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
let evens = arr.compactMap { $0 % 2 == 0 ? $0 : nil }
if evens.isEmpty { return [] }
let minEven = evens.min() ?? 0
return [minEven, arr.firstIndex(of: minEven) ?? 0]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
let evens = arr.compactMap { $0 % 2 == 0 ? $0 : nil }
if evens.isEmpty { return [] }
let minEven = evens.min() ?? 0
return [minEven, arr.firstIndex(of: minEven) ?? 0]
}
```
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
let evens = arr.filter { $0 % 2 == 0 }
if evens.isEmpty { return [] }
let smallestEven = evens.min() ?? 0
return [smallestEven, arr.firstIndex(of: smallestEven) ?? 0]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
let evens = arr.filter { $0 % 2 == 0 }
if evens.isEmpty { return [] }
let smallestEven = evens.min() ?? 0
return [smallestEven, arr.firstIndex(of: smallestEven) ?? 0]
}
```
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
let evens = arr.filter { $0 % 2 == 0 }
guard !evens.isEmpty else { return [] }
let smallestEven = evens.min()!
let smallestEvenIndexes = arr.enumerated().filter { $0.element == smallestEven }
let smallestEvenIndex = smallestEvenIndexes.min { $0.offset < $1.offset }!.offset
return [smallestEven, smallestEvenIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
let evens = arr.filter { $0 % 2 == 0 }
guard !evens.isEmpty else { return [] }
let smallestEven = evens.min()!
let smallestEvenIndexes = arr.enumerated().filter { $0.element == smallestEven }
let smallestEvenIndex = smallestEvenIndexes.min { $0.offset < $1.offset }!.offset
return [smallestEven, smallestEvenIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var evens = arr.filter { $0 % 2 == 0 }
guard evens.isEmpty == false else {
return []
}
var min = evens.min() ?? 0
var index = arr.firstIndex(of: min) ?? 0
return [min, index]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var evens = arr.filter { $0 % 2 == 0 }
guard evens.isEmpty == false else {
return []
}
var min = evens.min() ?? 0
var index = arr.firstIndex(of: min) ?? 0
return [min, index]
}
```
var evens = arr.filter { $0 % 2 == 0 } // variable 'evens' was never mutated; consider changing to 'let' constant
var min = evens.min() ?? 0 // variable 'min' was never mutated; consider changing to 'let' constant
var index = arr.firstIndex(of: min) ?? 0 // variable 'index' was never mutated; consider changing to 'let' constant
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
var smallestEven: Int = Int.max
var smallestIndex: Int = arr.count
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < smallestEven {
smallestEven = value
smallestIndex = index
}
else if value == smallestEven {
if index < smallestIndex {
smallestIndex = index
}
}
}
}
if smallestEven == Int.max { return [] }
return [smallestEven, smallestIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty { return [] }
var smallestEven: Int = Int.max
var smallestIndex: Int = arr.count
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < smallestEven {
smallestEven = value
smallestIndex = index
}
else if value == smallestEven {
if index < smallestIndex {
smallestIndex = index
}
}
}
}
if smallestEven == Int.max { return [] }
return [smallestEven, smallestIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = -1
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if smallestEvenValue == -1 {
smallestEvenValue = value
smallestEvenValueIndex = index
} else if value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
} else if value == smallestEvenValue && index < smallestEvenValueIndex {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
}
return [smallestEvenValue, smallestEvenValueIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = -1
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if smallestEvenValue == -1 {
smallestEvenValue = value
smallestEvenValueIndex = index
} else if value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
} else if value == smallestEvenValue && index < smallestEvenValueIndex {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
}
return [smallestEvenValue, smallestEvenValueIndex]
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var index = -1
for (i, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
index = i
}
}
if index == -1 {
return []
}
return [smallestEvenValue, 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 smallestEvenValue = Int.max
var index = -1
for (i, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
index = i
}
}
if index == -1 {
return []
}
return [smallestEvenValue, index]
}
```
func pluck(arr: [Int]) -> [Int] {
var evens = arr.compactMap { $0 % 2 == 0 ? $0 : nil }
evens.sort()
guard let smallest = evens.first else { return [] }
return [smallest, arr.firstIndex(of: smallest)!]
}
```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 evens = arr.compactMap { $0 % 2 == 0 ? $0 : nil }
evens.sort()
guard let smallest = evens.first else { return [] }
return [smallest, arr.firstIndex(of: smallest)!]
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if dict.keys.contains(i) {
dict[i]! += 1
} else {
dict[i] = 1
}
}
for (k, v) in dict {
if k == v {
return k
}
}
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 {
if dict.keys.contains(i) {
dict[i]! += 1
} else {
dict[i] = 1
}
}
for (k, v) in dict {
if k == v {
return k
}
}
return -1
}
```
// XCTAssertTrue failed
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 key >= 1 && 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 result = -1
var dict = [Int:Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if key >= 1 && value >= key {
result = key
}
}
return result
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
var max = 0
var result = -1
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
if dict[i] ?? 0 > i {
if max < i {
result = i
max = i
}
}
}
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]()
var max = 0
var result = -1
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
if dict[i] ?? 0 > i {
if max < i {
result = i
max = i
}
}
}
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
}
}
for (key, value) in dict {
if key < value {
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 {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
for (key, value) in dict {
if key < value {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
var max = -1
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
if dict[i]! >= i {
max = max > i ? max : i
}
}
return max
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
var max = -1
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
if dict[i]! >= i {
max = max > i ? max : i
}
}
return max
}
```
func search(lst: [Int]) -> Int {
var result = -1
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i]! + 1
}
}
for (key, value) in dict {
if key == value {
result = key
break
}
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var result = -1
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i]! + 1
}
}
for (key, value) in dict {
if key == value {
result = key
break
}
}
return result
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
var max = 0
var maxKey = 0
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
if dict[i]! > max {
max = dict[i]!
maxKey = i
}
}
if max < maxKey {
return -1
}
return maxKey
}
```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]()
var max = 0
var maxKey = 0
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
if dict[i]! > max {
max = dict[i]!
maxKey = i
}
}
if max < maxKey {
return -1
}
return maxKey
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
var max = -1
for i in lst {
dict[i, default: 0] += 1
if i > max {
max = i
}
}
var count = 0
for (k, v) in dict {
if k > 0 && v >= k {
count += 1
}
}
if count == 0 {
return -1
}
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]()
var max = -1
for i in lst {
dict[i, default: 0] += 1
if i > max {
max = i
}
}
var count = 0
for (k, v) in dict {
if k > 0 && v >= k {
count += 1
}
}
if count == 0 {
return -1
}
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
}
}
for (key, value) in dict {
if key > 0 && key <= value {
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 {
if dict[i] != nil {
dict[i]! += 1
} else {
dict[i] = 1
}
}
for (key, value) in dict {
if key > 0 && key <= value {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList = lst
var resultList = [Int]()
while sortedList.count > 0 {
resultList.append(sortedList.min()!)
resultList.append(sortedList.max()!)
sortedList.remove(at: sortedList.firstIndex(of: resultList.last!)!)
sortedList.remove(at: sortedList.firstIndex(of: resultList.first!)!)
}
return resultList
}
```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 sortedList = lst
var resultList = [Int]()
while sortedList.count > 0 {
resultList.append(sortedList.min()!)
resultList.append(sortedList.max()!)
sortedList.remove(at: sortedList.firstIndex(of: resultList.last!)!)
sortedList.remove(at: sortedList.firstIndex(of: resultList.first!)!)
}
return resultList
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
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 sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList: [Int] = []
var list: [Int] = lst
while list.count != 0 {
let min = list.min() ?? 0
sortedList.append(min)
list.remove(at: list.firstIndex(of: min)!)
let max = list.max() ?? 0
sortedList.append(max)
list.remove(at: list.firstIndex(of: max)!)
}
return sortedList
}
```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 sortedList: [Int] = []
var list: [Int] = lst
while list.count != 0 {
let min = list.min() ?? 0
sortedList.append(min)
list.remove(at: list.firstIndex(of: min)!)
let max = list.max() ?? 0
sortedList.append(max)
list.remove(at: list.firstIndex(of: max)!)
}
return sortedList
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = [Int]()
var sortedList = lst.sorted()
var i = 0
while sortedList.count > 0 {
sorted.append(sortedList.removeFirst())
sorted.append(sortedList.removeLast())
i += 1
}
return sorted
}
```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 sorted = [Int]()
var sortedList = lst.sorted()
var i = 0
while sortedList.count > 0 {
sorted.append(sortedList.removeFirst())
sorted.append(sortedList.removeLast())
i += 1
}
return sorted
}
```
// Fatal error: Can't remove last element from an empty collection
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList = lst
sortedList.sort()
var result = [Int]()
for i in 0...sortedList.count/2 {
result.append(sortedList[i])
result.append(sortedList[sortedList.count - i - 1])
}
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 sortedList = lst
sortedList.sort()
var result = [Int]()
for i in 0...sortedList.count/2 {
result.append(sortedList[i])
result.append(sortedList[sortedList.count - i - 1])
}
return result
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList: [Int] = []
var tempList: [Int] = lst
var min: Int = 0
var max: Int = 0
while tempList.count > 0 {
min = tempList.min()!
max = tempList.max()!
if tempList.count % 2 == 0 {
sortedList.append(min)
sortedList.append(max)
} else {
sortedList.append(max)
sortedList.append(min)
}
tempList = tempList.filter { $0 != min }
tempList = tempList.filter { $0 != max }
}
return sortedList
}
```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 sortedList: [Int] = []
var tempList: [Int] = lst
var min: Int = 0
var max: Int = 0
while tempList.count > 0 {
min = tempList.min()!
max = tempList.max()!
if tempList.count % 2 == 0 {
sortedList.append(min)
sortedList.append(max)
} else {
sortedList.append(max)
sortedList.append(min)
}
tempList = tempList.filter { $0 != min }
tempList = tempList.filter { $0 != max }
}
return sortedList
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
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 sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.removeFirst())
if !sorted.isEmpty {
result.append(sorted.removeLast())
}
}
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 sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.removeFirst())
if !sorted.isEmpty {
result.append(sorted.removeLast())
}
}
return result
}
```
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList: [Int] = []
var tempList: [Int] = lst
while !tempList.isEmpty {
let min = tempList.min()
let max = tempList.max()
tempList.remove(at: tempList.firstIndex(of: min!)!)
tempList.remove(at: tempList.firstIndex(of: max!)!)
sortedList.append(min!)
sortedList.append(max!)
}
return sortedList
}
```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 sortedList: [Int] = []
var tempList: [Int] = lst
while !tempList.isEmpty {
let min = tempList.min()
let max = tempList.max()
tempList.remove(at: tempList.firstIndex(of: min!)!)
tempList.remove(at: tempList.firstIndex(of: max!)!)
sortedList.append(min!)
sortedList.append(max!)
}
return sortedList
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList = [Int]()
var sortedListIndex = 0
var sortedListCount = 0
var sortedListMax = 0
var sortedListMin = 0
if lst.isEmpty {
return []
}
for i in lst {
if i > sortedListMax {
sortedListMax = i
}
if i < sortedListMin {
sortedListMin = i
}
}
sortedListCount = lst.count
while sortedListCount > 0 {
sortedList.insert(sortedListMin, at: sortedListIndex)
sortedListCount -= 1
sortedListIndex += 1
sortedList.insert(sortedListMax, at: sortedListIndex)
sortedListCount -= 1
sortedListIndex += 1
sortedListMax = 0
sortedListMin = 0
for i in lst {
if i > sortedListMax && i != sortedList[sortedListIndex - 1] {
sortedListMax = i
}
if i < sortedListMin && i != sortedList[sortedListIndex - 1] {
sortedListMin = i
}
}
}
return sortedList
}
```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 sortedList = [Int]()
var sortedListIndex = 0
var sortedListCount = 0
var sortedListMax = 0
var sortedListMin = 0
if lst.isEmpty {
return []
}
for i in lst {
if i > sortedListMax {
sortedListMax = i
}
if i < sortedListMin {
sortedListMin = i
}
}
sortedListCount = lst.count
while sortedListCount > 0 {
sortedList.insert(sortedListMin, at: sortedListIndex)
sortedListCount -= 1
sortedListIndex += 1
sortedList.insert(sortedListMax, at: sortedListIndex)
sortedListCount -= 1
sortedListIndex += 1
sortedListMax = 0
sortedListMin = 0
for i in lst {
if i > sortedListMax && i != sortedList[sortedListIndex - 1] {
sortedListMax = i
}
if i < sortedListMin && i != sortedList[sortedListIndex - 1] {
sortedListMin = i
}
}
}
return sortedList
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// 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 {
// your code here
}
```
} // missing return in global function expected to return 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
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 s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
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 s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s) * (Double(s) - Double(a)) * (Double(s) - Double(b)) * (Double(s) - Double(c)))
if (a + b > c && a + c > b && b + c > a) {
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 s = (a + b + c) / 2
let area = sqrt(Double(s) * (Double(s) - Double(a)) * (Double(s) - Double(b)) * (Double(s) - Double(c)))
if (a + b > c && a + c > b && b + c > a) {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
return round(area * 100) / 100
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
return round(area * 100) / 100
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
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 s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
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 s = (a + b + c) / 2
let area = sqrt(Double(s * (s - a) * (s - b) * (s - c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
var s = Double(a + b + c) / 2
if a + b > c && a + c > b && b + c > a {
return sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - 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 {
var s = Double(a + b + c) / 2
if a + b > c && a + c > b && b + c > a {
return sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
} else {
return -1
}
}
```
var s = Double(a + b + c) / 2 // variable 's' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
var area = 0.0
if a + b > c && a + c > b && b + c > a {
let s = (a + b + c) / 2.0
area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
}
return area
}
```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 {
var area = 0.0
if a + b > c && a + c > b && b + c > a {
let s = (a + b + c) / 2.0
area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
}
return area
}
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && a + c > b && b + c > a {
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && a + c > b && b + c > a {
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w { return false }
let reversed = q.reversed()
let isPalindrome = q == reversed
return isPalindrome
}
```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, +)
if sum > w { return false }
let reversed = q.reversed()
let isPalindrome = q == reversed
return isPalindrome
}
```
let isPalindrome = q == reversed // cannot convert value of type 'ReversedCollection<[Int]>' to expected argument type '[Int]'
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```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 isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q == 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 == q.reversed()
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q.count % 2 == 0 ? q.first == q.last : q.count == 1
return sum <= w && isBalanced
}
```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 isBalanced = q.count % 2 == 0 ? q.first == q.last : q.count == 1
return sum <= w && isBalanced
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q == 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 == q.reversed()
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```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 isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```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 isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q == 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 == q.reversed()
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q == 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 == q.reversed()
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```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 isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```
func smallestChange(arr: [Int]) -> Int {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func smallestChange(arr: [Int]) -> Int {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return 'Int'
func smallestChange(arr: [Int]) -> Int {
// Write your code here
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 {
// Write your code here
return 0
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
// Write your code here.
}
```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 {
// Write your code here.
}
```
} // missing return in global function expected to return '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
}
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
}
```
func smallestChange(arr: [Int]) -> Int {
// Write your code here.
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 {
// Write your code here.
return 0
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
return 1
}
left += 1
right -= 1
}
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 left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
return 1
}
left += 1
right -= 1
}
return 0
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var changes = 0
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
changes += 1
if arr[left] < arr[right] {
left += 1
} else {
right -= 1
}
}
}
return changes
}
```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 left = 0
var right = arr.count - 1
var changes = 0
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
changes += 1
if arr[left] < arr[right] {
left += 1
} else {
right -= 1
}
}
}
return changes
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
// Write your code here.
var left = 0
var right = arr.count - 1
var count = 0
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 {
// Write your code here.
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left] != arr[right] {
count += 1
}
left += 1
right -= 1
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
count += 1
if arr[left] > arr[right] {
right -= 1
} else {
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 left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
count += 1
if arr[left] > arr[right] {
right -= 1
} else {
left += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
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 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 {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var 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 {
return lst2
}
}
```
// XCTAssertTrue failed
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 {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var 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 {
return lst2
}
}
```
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var lst1TotalChars: Int = 0
var lst2TotalChars: Int = 0
for char in lst1 {
lst1TotalChars += char.count
}
for char in lst2 {
lst2TotalChars += char.count
}
if lst1TotalChars < lst2TotalChars {
return lst1
} else if lst2TotalChars < lst1TotalChars {
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 lst1TotalChars: Int = 0
var lst2TotalChars: Int = 0
for char in lst1 {
lst1TotalChars += char.count
}
for char in lst2 {
lst2TotalChars += char.count
}
if lst1TotalChars < lst2TotalChars {
return lst1
} else if lst2TotalChars < lst1TotalChars {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var lst1Chars = 0
var lst2Chars = 0
var lst1Result = [String]()
var lst2Result = [String]()
for item in lst1 {
lst1Chars += item.count
}
for item in lst2 {
lst2Chars += item.count
}
if lst1Chars < lst2Chars {
lst1Result = lst1
} else if lst1Chars > lst2Chars {
lst2Result = lst2
} else {
lst1Result = lst1
}
return lst1Result
}
```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 lst1Chars = 0
var lst2Chars = 0
var lst1Result = [String]()
var lst2Result = [String]()
for item in lst1 {
lst1Chars += item.count
}
for item in lst2 {
lst2Chars += item.count
}
if lst1Chars < lst2Chars {
lst1Result = lst1
} else if lst1Chars > lst2Chars {
lst2Result = lst2
} else {
lst1Result = lst1
}
return lst1Result
}
```
var lst2Result = [String]() // variable 'lst2Result' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var sum1 = 0
var sum2 = 0
for i in lst1 {
sum1 += i.count
}
for i in lst2 {
sum2 += i.count
}
if sum1 < sum2 {
return lst1
} else if sum1 > sum2 {
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 sum1 = 0
var sum2 = 0
for i in lst1 {
sum1 += i.count
}
for i in lst2 {
sum2 += i.count
}
if sum1 < sum2 {
return lst1
} else if sum1 > sum2 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var lst1Chars = 0
var lst2Chars = 0
for i in lst1 {
lst1Chars += i.count
}
for i in lst2 {
lst2Chars += i.count
}
if lst1Chars < lst2Chars {
return lst1
} else if lst2Chars < lst1Chars {
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 lst1Chars = 0
var lst2Chars = 0
for i in lst1 {
lst1Chars += i.count
}
for i in lst2 {
lst2Chars += i.count
}
if lst1Chars < lst2Chars {
return lst1
} else if lst2Chars < lst1Chars {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
// your code here
let lst1Chars = lst1.reduce(0) { $0 + $1.count }
let lst2Chars = lst2.reduce(0) { $0 + $1.count }
return lst1Chars <= lst2Chars ? lst1 : lst2
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
// your code here
let lst1Chars = lst1.reduce(0) { $0 + $1.count }
let lst2Chars = lst2.reduce(0) { $0 + $1.count }
return lst1Chars <= lst2Chars ? lst1 : lst2
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var lst1Count = 0
var lst2Count = 0
for word in lst1 {
lst1Count += word.count
}
for word in lst2 {
lst2Count += word.count
}
if lst1Count < lst2Count {
return lst1
} else if lst1Count > lst2Count {
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 lst1Count = 0
var lst2Count = 0
for word in lst1 {
lst1Count += word.count
}
for word in lst2 {
lst2Count += word.count
}
if lst1Count < lst2Count {
return lst1
} else if lst1Count > lst2Count {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let sum1 = lst1.map { $0.count }.reduce(0, +)
let sum2 = lst2.map { $0.count }.reduce(0, +)
return sum1 < sum2 ? lst1 : lst2
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let sum1 = lst1.map { $0.count }.reduce(0, +)
let sum2 = lst2.map { $0.count }.reduce(0, +)
return sum1 < sum2 ? lst1 : lst2
}
```
// 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 {
// 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 {
var isMultiply = false
var count = 0
var i = 2
while i < a {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 2 {
isMultiply = true
}
return isMultiply
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiply = false
var count = 0
var i = 2
while i < a {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 2 {
isMultiply = true
}
return isMultiply
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
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 {
// Write your code here
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = true
var isMultiple = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
if count == 3 {
isMultiple = true
break
}
isPrime = false
i += 1
} else {
i += 1
}
}
return isMultiple
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = true
var isMultiple = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
if count == 3 {
isMultiple = true
break
}
isPrime = false
i += 1
} else {
i += 1
}
}
return isMultiple
}
```
var isPrime = true // variable 'isPrime' was written to, but never read
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var primeNumbers = [Int]()
var count = 0
for number in 2...a {
if isPrime(number: number) {
primeNumbers.append(number)
}
}
for i in 0...primeNumbers.count {
for j in i+1...primeNumbers.count {
for k in j+1...primeNumbers.count {
if primeNumbers[i] * primeNumbers[j] * primeNumbers[k] == a {
isMultiplyPrime = true
count += 1
}
}
}
}
if count > 1 {
isMultiplyPrime = false
}
return isMultiplyPrime
}
func isPrime(number: Int) -> Bool {
var isPrime = true
for i in 2..<number {
if number % i == 0 {
isPrime = false
break
}
}
return isPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var primeNumbers = [Int]()
var count = 0
for number in 2...a {
if isPrime(number: number) {
primeNumbers.append(number)
}
}
for i in 0...primeNumbers.count {
for j in i+1...primeNumbers.count {
for k in j+1...primeNumbers.count {
if primeNumbers[i] * primeNumbers[j] * primeNumbers[k] == a {
isMultiplyPrime = true
count += 1
}
}
}
}
if count > 1 {
isMultiplyPrime = false
}
return isMultiplyPrime
}
func isPrime(number: Int) -> Bool {
var isPrime = true
for i in 2..<number {
if number % i == 0 {
isPrime = false
break
}
}
return isPrime
}
```
// Fatal error: Index out of range
func isMultiplyPrime(a: Int) -> Bool {
// your code here
var isPrime = true
for i in 2...a {
if a % i == 0 {
if i == 2 || i == 3 {
return true
} else {
return false
}
}
}
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 {
// your code here
var isPrime = true
for i in 2...a {
if a % i == 0 {
if i == 2 || i == 3 {
return true
} else {
return false
}
}
}
return false
}
```
var isPrime = true // initialization of variable 'isPrime' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
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 {
// Write your code here
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 3 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 3 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
for i in primeNumbers {
for j in primeNumbers {
for k in primeNumbers {
if a == i * j * k {
isMultiplyPrime = true
break
}
}
}
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
for i in primeNumbers {
for j in primeNumbers {
for k in primeNumbers {
if a == i * j * k {
isMultiplyPrime = true
break
}
}
}
}
return isMultiplyPrime
}
```
var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] // variable 'primeNumbers' was never mutated; consider changing to 'let' constant
func isSimplePower(x: Int, n: Int) -> Bool {
let result = x.squareRoot()
if result.truncatingRemainder(dividingBy: 1) == 0 {
return true
} else {
return false
}
}
```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 {
let result = x.squareRoot()
if result.truncatingRemainder(dividingBy: 1) == 0 {
return true
} else {
return false
}
}
```
let result = x.squareRoot() // value of type 'Int' has no member 'squareRoot'
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n**Int(log(Double(x)) / log(Double(n)))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n**Int(log(Double(x)) / log(Double(n)))
}
```
return x == n**Int(log(Double(x)) / log(Double(n))) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func isSimplePower(x: Int, n: Int) -> Bool {
let int = Int(log(Double(x))/log(Double(n)))
return x == pow(n, int)
}
```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 {
let int = Int(log(Double(x))/log(Double(n)))
return x == pow(n, int)
}
```
return x == pow(n, int) // cannot convert value of type 'Int' to expected argument type 'Decimal'
return x == pow(n, int) // operator function '==' requires that 'Decimal' conform to 'BinaryInteger'
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n.pow(n: Int(log(Double(x))/log(Double(n))))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n.pow(n: Int(log(Double(x))/log(Double(n))))
}
```
return x == n.pow(n: Int(log(Double(x))/log(Double(n)))) // value of type 'Int' has no member 'pow'
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n**Int(log(Double(x)) / log(Double(n)))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n**Int(log(Double(x)) / log(Double(n)))
}
```
return x == n**Int(log(Double(x)) / log(Double(n))) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func isSimplePower(x: Int, n: Int) -> Bool {
return x == pow(Double(n), Double(x))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == pow(Double(n), Double(x))
}
```
return x == pow(Double(n), Double(x)) // cannot convert value of type 'Double' to expected argument type 'Int'
func isSimplePower(x: Int, n: Int) -> Bool {
return x == pow(Double(n), Double(x))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == pow(Double(n), Double(x))
}
```
return x == pow(Double(n), Double(x)) // cannot convert value of type 'Double' to expected argument type 'Int'
func isSimplePower(x: Int, n: Int) -> Bool {
if x == n {
return true
}
var i = 1
var result = n
while result < x {
result = n * i
if result == x {
return true
}
i += 1
}
return false
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
if x == n {
return true
}
var i = 1
var result = n
while result < x {
result = n * i
if result == x {
return true
}
i += 1
}
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
if n == 1 { return false }
if n == x { return true }
if x % n != 0 { return false }
return isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
if n == 1 { return false }
if n == x { return true }
if x % n != 0 { return false }
return isSimplePower(x: x / n, n: n)
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n*n
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n*n
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
return Int(pow(Double(a), 1/3.0)) * Int(pow(Double(a), 1/3.0)) == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(pow(Double(a), 1/3.0)) * Int(pow(Double(a), 1/3.0)) == a
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
return a == Int(pow(Double(a), 1/3))
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return a == Int(pow(Double(a), 1/3))
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
return Int(pow(Double(a), 1/3)) == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(pow(Double(a), 1/3)) == a
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
let cube = a * a * a
if (a == 0) {
return true
} else if (cube == a) {
return true
} else {
return false
}
}
```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 = a * a * a
if (a == 0) {
return true
} else if (cube == a) {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
return a == Int(pow(Double(a), 1/3))
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return a == Int(pow(Double(a), 1/3))
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
let cube = Int(pow(Double(a), 1.0/3.0))
if a == cube*cube*cube {
return true
} else {
return false
}
}
```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))
if a == cube*cube*cube {
return true
} else {
return false
}
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
let cube = Int(pow(Double(a), 1/3))
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/3))
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 {
let cube = a * a * a
if a == cube {
return true
} else {
return false
}
}
```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 = a * a * a
if a == cube {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
return a == Int(pow(Double(a), 1/3))
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return a == Int(pow(Double(a), 1/3))
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
let cube = a ** (1/3)
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 = a ** (1/3)
return cube * cube * cube == a
}
```
let cube = a ** (1/3) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func hexKey(num: String) -> Int {
let hexDigits = "0123456789ABCDEF"
let primeHexDigits = "2357BD"
var count = 0
for hex in num {
if primeHexDigits.contains(hex) {
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 hexDigits = "0123456789ABCDEF"
let primeHexDigits = "2357BD"
var count = 0
for hex in num {
if primeHexDigits.contains(hex) {
count += 1
}
}
return count
}
```
let hexDigits = "0123456789ABCDEF" // initialization of immutable value 'hexDigits' was never used; consider replacing with assignment to '_' or removing it
func hexKey(num: String) -> Int {
let hexDigits = ["2","3","5","7","B","D"]
var count = 0
for char in num {
if hexDigits.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 hexDigits = ["2","3","5","7","B","D"]
var count = 0
for char in num {
if hexDigits.contains(String(char)) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
let hexDigits = "0123456789ABCDEF"
let primes = [2, 3, 5, 7, 11, 13]
var count = 0
for char in num {
if let index = hexDigits.firstIndex(of: char) {
if primes.contains(Int(String(hexDigits[index]), radix: 16)!) {
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 hexDigits = "0123456789ABCDEF"
let primes = [2, 3, 5, 7, 11, 13]
var count = 0
for char in num {
if let index = hexDigits.firstIndex(of: char) {
if primes.contains(Int(String(hexDigits[index]), radix: 16)!) {
count += 1
}
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
let hexDigits = ["2","3","5","7","B","D"]
var count = 0
for char in num {
if hexDigits.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 hexDigits = ["2","3","5","7","B","D"]
var count = 0
for char in num {
if hexDigits.contains(String(char)) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
let hex = num.uppercased()
var count = 0
for i in hex {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
let hex = num.uppercased()
var count = 0
for i in hex {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
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 {
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 decimalToBinary(decimal: Int) -> String {
var binary = ""
var number = decimal
while number > 0 {
binary = String(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 = String(number % 2) + binary
number /= 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
let db = "db"
return db + binary + db
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
let db = "db"
return db + binary + db
}
```
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var number = decimal
while number > 0 {
let remainder = number % 2
number = number / 2
binary = String(remainder) + binary
}
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 {
let remainder = number % 2
number = number / 2
binary = String(remainder) + binary
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```
func decimalToBinary(decimal: Int) -> String {
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 {
var binary = ""
var decimal = decimal
while decimal > 0 {
let remainder = decimal % 2
binary = "\(remainder)" + binary
decimal = 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 {
let remainder = decimal % 2
binary = "\(remainder)" + binary
decimal = decimal / 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 = 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 = decimal / 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 binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "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 isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count {
let start = s.index(s.startIndex, offsetBy: i)
let end = s.index(start, offsetBy: 2)
let substring = s[start..<end]
if substring.containsDuplicate() {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count {
let start = s.index(s.startIndex, offsetBy: i)
let end = s.index(start, offsetBy: 2)
let substring = s[start..<end]
if substring.containsDuplicate() {
return false
}
}
return true
}
```
if substring.containsDuplicate() { // value of type 'Substring' has no member 'containsDuplicate'
func isHappy(s: String) -> Bool {
// Write your code here
if s.count < 3 {
return false
}
for i in 0..<s.count {
if i+2 < s.count {
let c = s[i..<i+3]
if c.count == c.characters.count {
return true
}
}
}
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 {
// Write your code here
if s.count < 3 {
return false
}
for i in 0..<s.count {
if i+2 < s.count {
let c = s[i..<i+3]
if c.count == c.characters.count {
return true
}
}
}
return false
}
```
let c = s[i..<i+3] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if c.count == c.characters.count { // 'characters' is unavailable: Please use String directly
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in stride(from: 0, to: s.count, by: 3) {
let sub = s.dropFirst(i).prefix(3)
if set.contains(where: { $0 == 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 stride(from: 0, to: s.count, by: 3) {
let sub = s.dropFirst(i).prefix(3)
if set.contains(where: { $0 == sub }) { return false }
set.insert(sub)
}
return true
}
```
if set.contains(where: { $0 == sub }) { return false } // cannot convert value of type 'Substring.SubSequence' (aka 'Substring') to expected argument type 'Character'
set.insert(sub) // cannot convert value of type 'Substring.SubSequence' (aka 'Substring') to expected argument type 'Character'
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
var set = Set<Character>()
for i in stride(from: 0, to: s.count, by: 3) {
guard i + 2 < s.count else { return false }
let range = s.index(s.startIndex, offsetBy: i)..<s.index(s.startIndex, offsetBy: i + 3)
let substring = s[range]
if set.contains(contentsOf: substring) { return false }
set.formUnion(substring)
}
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 stride(from: 0, to: s.count, by: 3) {
guard i + 2 < s.count else { return false }
let range = s.index(s.startIndex, offsetBy: i)..<s.index(s.startIndex, offsetBy: i + 3)
let substring = s[range]
if set.contains(contentsOf: substring) { return false }
set.formUnion(substring)
}
return true
}
```
if set.contains(contentsOf: substring) { return false } // extraneous argument label 'contentsOf:' in call
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
var set = Set<Character>()
for i in 0..<s.count - 2 {
let a = s[s.index(s.startIndex, offsetBy: i)]
let b = s[s.index(s.startIndex, offsetBy: i + 1)]
let c = s[s.index(s.startIndex, offsetBy: i + 2)]
set.insert(a)
set.insert(b)
set.insert(c)
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 {
if s.count < 3 {
return false
}
var set = Set<Character>()
for i in 0..<s.count - 2 {
let a = s[s.index(s.startIndex, offsetBy: i)]
let b = s[s.index(s.startIndex, offsetBy: i + 1)]
let c = s[s.index(s.startIndex, offsetBy: i + 2)]
set.insert(a)
set.insert(b)
set.insert(c)
if set.count == 3 {
return true
}
set.removeAll()
}
return false
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i+1)] ||
s[s.index(s.startIndex, offsetBy: i+1)] == s[s.index(s.startIndex, offsetBy: i+2)] ||
s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i+2)] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i+1)] ||
s[s.index(s.startIndex, offsetBy: i+1)] == s[s.index(s.startIndex, offsetBy: i+2)] ||
s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i+2)] {
return false
}
}
return true
}
```
func isHappy(s: String) -> Bool {
let str = s.map{String($0)}
if str.count < 3 {
return false
}
for i in 0...str.count-3 {
if str[i] == str[i+1] || str[i] == str[i+2] || str[i+1] == str[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let str = s.map{String($0)}
if str.count < 3 {
return false
}
for i in 0...str.count-3 {
if str[i] == str[i+1] || str[i] == str[i+2] || str[i+1] == str[i+2] {
return false
}
}
return true
}
```
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i+1] == chars[i+2] || chars[i] == chars[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i+1] == chars[i+2] || chars[i] == chars[i+2] {
return false
}
}
return true
}
```
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
let chars = s.map { String($0) }
for i in 0..<chars.count - 2 {
if chars[i] == chars[i + 1] || chars[i] == chars[i + 2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
let chars = s.map { String($0) }
for i in 0..<chars.count - 2 {
if chars[i] == chars[i + 1] || chars[i] == chars[i + 2] {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var s = s.map{String($0)}
if s.count < 3 {return false}
for i in stride(from: 0, to: s.count-2, by: 1){
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2]{
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var s = s.map{String($0)}
if s.count < 3 {return false}
for i in stride(from: 0, to: s.count-2, by: 1){
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2]{
return false
}
}
return true
}
```
var s = s.map{String($0)} // variable 's' was never mutated; consider changing to 'let' constant
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
}
```
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
switch grade {
case 4.0:
letterGrades.append("A+")
case 3.7...:
letterGrades.append("A")
case 3.3...:
letterGrades.append("A-")
case 3.0...:
letterGrades.append("B+")
case 2.7...:
letterGrades.append("B")
case 2.3...:
letterGrades.append("B-")
case 2.0...:
letterGrades.append("C+")
case 1.7...:
letterGrades.append("C")
case 1.3...:
letterGrades.append("C-")
case 1.0...:
letterGrades.append("D+")
case 0.7...:
letterGrades.append("D")
case 0.0:
letterGrades.append("D-")
default:
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 {
switch grade {
case 4.0:
letterGrades.append("A+")
case 3.7...:
letterGrades.append("A")
case 3.3...:
letterGrades.append("A-")
case 3.0...:
letterGrades.append("B+")
case 2.7...:
letterGrades.append("B")
case 2.3...:
letterGrades.append("B-")
case 2.0...:
letterGrades.append("C+")
case 1.7...:
letterGrades.append("C")
case 1.3...:
letterGrades.append("C-")
case 1.0...:
letterGrades.append("D+")
case 0.7...:
letterGrades.append("D")
case 0.0:
letterGrades.append("D-")
default:
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7...4.0:
letterGrade.append("A")
case 3.3...3.7:
letterGrade.append("A-")
case 3.0...3.3:
letterGrade.append("B+")
case 2.7...3.0:
letterGrade.append("B")
case 2.3...2.7:
letterGrade.append("B-")
case 2.0...2.3:
letterGrade.append("C+")
case 1.7...2.0:
letterGrade.append("C")
case 1.3...1.7:
letterGrade.append("C-")
case 1.0...1.3:
letterGrade.append("D+")
case 0.7...1.0:
letterGrade.append("D")
case 0.0...0.7:
letterGrade.append("D-")
default:
letterGrade.append("E")
}
}
return letterGrade
}
```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 letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7...4.0:
letterGrade.append("A")
case 3.3...3.7:
letterGrade.append("A-")
case 3.0...3.3:
letterGrade.append("B+")
case 2.7...3.0:
letterGrade.append("B")
case 2.3...2.7:
letterGrade.append("B-")
case 2.0...2.3:
letterGrade.append("C+")
case 1.7...2.0:
letterGrade.append("C")
case 1.3...1.7:
letterGrade.append("C-")
case 1.0...1.3:
letterGrade.append("D+")
case 0.7...1.0:
letterGrade.append("D")
case 0.0...0.7:
letterGrade.append("D-")
default:
letterGrade.append("E")
}
}
return letterGrade
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7..<4.0:
letterGrade.append("A")
case 3.3..<3.7:
letterGrade.append("A-")
case 3.0..<3.3:
letterGrade.append("B+")
case 2.7..<3.0:
letterGrade.append("B")
case 2.3..<2.7:
letterGrade.append("B-")
case 2.0..<2.3:
letterGrade.append("C+")
case 1.7..<2.0:
letterGrade.append("C")
case 1.3..<1.7:
letterGrade.append("C-")
case 1.0..<1.3:
letterGrade.append("D+")
case 0.7..<1.0:
letterGrade.append("D")
case 0.0..<0.7:
letterGrade.append("D-")
case 0.0:
letterGrade.append("E")
default:
letterGrade.append("Error")
}
}
return letterGrade
}
```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 letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7..<4.0:
letterGrade.append("A")
case 3.3..<3.7:
letterGrade.append("A-")
case 3.0..<3.3:
letterGrade.append("B+")
case 2.7..<3.0:
letterGrade.append("B")
case 2.3..<2.7:
letterGrade.append("B-")
case 2.0..<2.3:
letterGrade.append("C+")
case 1.7..<2.0:
letterGrade.append("C")
case 1.3..<1.7:
letterGrade.append("C-")
case 1.0..<1.3:
letterGrade.append("D+")
case 0.7..<1.0:
letterGrade.append("D")
case 0.0..<0.7:
letterGrade.append("D-")
case 0.0:
letterGrade.append("E")
default:
letterGrade.append("Error")
}
}
return letterGrade
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrade: [String] = []
for grade in grades {
if grade == 4.0 {
letterGrade.append("A+")
} else if grade > 3.7 {
letterGrade.append("A")
} else if grade > 3.3 {
letterGrade.append("A-")
} else if grade > 3.0 {
letterGrade.append("B+")
} else if grade > 2.7 {
letterGrade.append("B")
} else if grade > 2.3 {
letterGrade.append("B-")
} else if grade > 2.0 {
letterGrade.append("C+")
} else if grade > 1.7 {
letterGrade.append("C")
} else if grade > 1.3 {
letterGrade.append("C-")
} else if grade > 1.0 {
letterGrade.append("D+")
} else if grade > 0.7 {
letterGrade.append("D")
} else if grade > 0.0 {
letterGrade.append("D-")
} else {
letterGrade.append("E")
}
}
return letterGrade
}
```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 letterGrade: [String] = []
for grade in grades {
if grade == 4.0 {
letterGrade.append("A+")
} else if grade > 3.7 {
letterGrade.append("A")
} else if grade > 3.3 {
letterGrade.append("A-")
} else if grade > 3.0 {
letterGrade.append("B+")
} else if grade > 2.7 {
letterGrade.append("B")
} else if grade > 2.3 {
letterGrade.append("B-")
} else if grade > 2.0 {
letterGrade.append("C+")
} else if grade > 1.7 {
letterGrade.append("C")
} else if grade > 1.3 {
letterGrade.append("C-")
} else if grade > 1.0 {
letterGrade.append("D+")
} else if grade > 0.7 {
letterGrade.append("D")
} else if grade > 0.0 {
letterGrade.append("D-")
} else {
letterGrade.append("E")
}
}
return letterGrade
}
```
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7...4.0:
letterGrade.append("A")
case 3.3...3.7:
letterGrade.append("A-")
case 3.0...3.3:
letterGrade.append("B+")
case 2.7...3.0:
letterGrade.append("B")
case 2.3...2.7:
letterGrade.append("B-")
case 2.0...2.3:
letterGrade.append("C+")
case 1.7...2.0:
letterGrade.append("C")
case 1.3...1.7:
letterGrade.append("C-")
case 1.0...1.3:
letterGrade.append("D+")
case 0.7...1.0:
letterGrade.append("D")
case 0.0...0.7:
letterGrade.append("D-")
default:
letterGrade.append("E")
}
}
return letterGrade
}
```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 letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7...4.0:
letterGrade.append("A")
case 3.3...3.7:
letterGrade.append("A-")
case 3.0...3.3:
letterGrade.append("B+")
case 2.7...3.0:
letterGrade.append("B")
case 2.3...2.7:
letterGrade.append("B-")
case 2.0...2.3:
letterGrade.append("C+")
case 1.7...2.0:
letterGrade.append("C")
case 1.3...1.7:
letterGrade.append("C-")
case 1.0...1.3:
letterGrade.append("D+")
case 0.7...1.0:
letterGrade.append("D")
case 0.0...0.7:
letterGrade.append("D-")
default:
letterGrade.append("E")
}
}
return letterGrade
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7..<4.0:
letterGrade.append("A")
case 3.3..<3.7:
letterGrade.append("A-")
case 3.0..<3.3:
letterGrade.append("B+")
case 2.7..<3.0:
letterGrade.append("B")
case 2.3..<2.7:
letterGrade.append("B-")
case 2.0..<2.3:
letterGrade.append("C+")
case 1.7..<2.0:
letterGrade.append("C")
case 1.3..<1.7:
letterGrade.append("C-")
case 1.0..<1.3:
letterGrade.append("D+")
case 0.7..<1.0:
letterGrade.append("D")
case 0.0..<0.7:
letterGrade.append("D-")
default:
letterGrade.append("E")
}
}
return letterGrade
}
```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 letterGrade: [String] = []
for grade in grades {
switch grade {
case 4.0:
letterGrade.append("A+")
case 3.7..<4.0:
letterGrade.append("A")
case 3.3..<3.7:
letterGrade.append("A-")
case 3.0..<3.3:
letterGrade.append("B+")
case 2.7..<3.0:
letterGrade.append("B")
case 2.3..<2.7:
letterGrade.append("B-")
case 2.0..<2.3:
letterGrade.append("C+")
case 1.7..<2.0:
letterGrade.append("C")
case 1.3..<1.7:
letterGrade.append("C-")
case 1.0..<1.3:
letterGrade.append("D+")
case 0.7..<1.0:
letterGrade.append("D")
case 0.0..<0.7:
letterGrade.append("D-")
default:
letterGrade.append("E")
}
}
return letterGrade
}
```
// 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
}
```
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
}
```
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade == 4 {
letterGrades.append("A+")
} else if grade > 3.7 {
letterGrades.append("A")
} else if grade > 3.3 {
letterGrades.append("A-")
} else if grade > 3 {
letterGrades.append("B+")
} else if grade > 2.7 {
letterGrades.append("B")
} else if grade > 2.3 {
letterGrades.append("B-")
} else if grade > 2 {
letterGrades.append("C+")
} else if grade > 1.7 {
letterGrades.append("C")
} else if grade > 1.3 {
letterGrades.append("C-")
} else if grade > 1 {
letterGrades.append("D+")
} else if grade > 0.7 {
letterGrades.append("D")
} else if grade > 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 {
letterGrades.append("A+")
} else if grade > 3.7 {
letterGrades.append("A")
} else if grade > 3.3 {
letterGrades.append("A-")
} else if grade > 3 {
letterGrades.append("B+")
} else if grade > 2.7 {
letterGrades.append("B")
} else if grade > 2.3 {
letterGrades.append("B-")
} else if grade > 2 {
letterGrades.append("C+")
} else if grade > 1.7 {
letterGrades.append("C")
} else if grade > 1.3 {
letterGrades.append("C-")
} else if grade > 1 {
letterGrades.append("D+")
} else if grade > 0.7 {
letterGrades.append("D")
} else if grade > 0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
let stringLength = string.count
if stringLength == 1 {
return false
}
for i in 2...stringLength / 2 {
if stringLength % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let stringLength = string.count
if stringLength == 1 {
return false
}
for i in 2...stringLength / 2 {
if stringLength % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
var result = 0
for i in 1...9 {
result += startsOneEnds(n: n - 1)
}
return result
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
var result = 0
for i in 1...9 {
result += startsOneEnds(n: n - 1)
}
return result
}
let n = 10
print(startsOneEnds(n: n))
```
for i in 1...9 { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 9 * startsOneEnds(n: n - 1)
}
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
func startsOneOrEndsOne(n: Int) -> Int {
if n == 1 {
return 2
}
return 18 * startsOneOrEndsOne(n: n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 9 * startsOneEnds(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 or end with 1.
func startsOneOrEndsOne(n: Int) -> Int {
if n == 1 {
return 2
}
return 18 * startsOneOrEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsOne
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 9 * startsOneEnds(n: n - 1)
}
func startsOneEndsTwo(n: Int) -> Int {
if n == 1 {
return 3
}
return 9 * startsOneEndsTwo(n: n - 1)
}
func startsOneEndsThree(n: Int) -> Int {
if n == 1 {
return 4
}
return 9 * startsOneEndsThree(n: n - 1)
}
func startsOneEndsFour(n: Int) -> Int {
if n == 1 {
return 5
}
return 9 * startsOneEndsFour(n: n - 1)
}
func startsOneEndsFive(n: Int) -> Int {
if n == 1 {
return 6
}
return 9 * startsOneEndsFive(n: n - 1)
}
func startsOneEndsSix(n: Int) -> Int {
if n == 1 {
return 7
}
return 9 * startsOneEndsSix(n: n - 1)
}
func startsOneEndsSeven(n: Int) -> Int {
if n == 1 {
return 8
}
return 9 * startsOneEndsSeven(n: n - 1)
}
func startsOneEndsEight(n: Int) -> Int {
if n == 1 {
return 9
}
return 9 * startsOneEndsEight(n: n - 1)
}
func startsOneEndsNine(n: Int) -> Int {
if n == 1 {
return 10
}
return 9 * startsOneEndsNine(n: n - 1)
}
func startsOneEndsTen(n: Int) -> Int {
if n == 1 {
return 11
}
return 9 * startsOneEndsTen(n: n - 1)
}
func startsOneEndsEleven(n: Int) -> Int {
if n == 1 {
return 12
}
return 9 * startsOneEndsEleven(n: n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 9 * startsOneEnds(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2.
func startsOneEndsTwo(n: Int) -> Int {
if n == 1 {
return 3
}
return 9 * startsOneEndsTwo(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3.
func startsOneEndsThree(n: Int) -> Int {
if n == 1 {
return 4
}
return 9 * startsOneEndsThree(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4.
func startsOneEndsFour(n: Int) -> Int {
if n == 1 {
return 5
}
return 9 * startsOneEndsFour(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5.
func startsOneEndsFive(n: Int) -> Int {
if n == 1 {
return 6
}
return 9 * startsOneEndsFive(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5 or 6.
func startsOneEndsSix(n: Int) -> Int {
if n == 1 {
return 7
}
return 9 * startsOneEndsSix(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5 or 6 or 7.
func startsOneEndsSeven(n: Int) -> Int {
if n == 1 {
return 8
}
return 9 * startsOneEndsSeven(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8.
func startsOneEndsEight(n: Int) -> Int {
if n == 1 {
return 9
}
return 9 * startsOneEndsEight(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9.
func startsOneEndsNine(n: Int) -> Int {
if n == 1 {
return 10
}
return 9 * startsOneEndsNine(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 0.
func startsOneEndsTen(n: Int) -> Int {
if n == 1 {
return 11
}
return 9 * startsOneEndsTen(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 0 or 1.
func startsOneEndsEleven(n: Int) -> Int {
if n == 1 {
return 12
}
return 9 * startsOneEndsEleven(n: n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
var count = 0
for i in 1...9 {
count += startsOneEnds(n: n - 1)
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
var count = 0
for i in 1...9 {
count += startsOneEnds(n: n - 1)
}
return count
}
```
for i in 1...9 { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
if n == 2 {
return 11
}
var count = 0
for i in 1..<10 {
count += startsOneEnds(n: n-1)
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
if n == 2 {
return 11
}
var count = 0
for i in 1..<10 {
count += startsOneEnds(n: n-1)
}
return count
}
```
for i in 1..<10 { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
if n == 2 {
return 10
}
return 9 * startsOneEnds(n: n - 1) + 8 * startsOneEnds(n: n - 2)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
if n == 2 {
return 10
}
return 9 * startsOneEnds(n: n - 1) + 8 * startsOneEnds(n: n - 2)
}
startsOneEnds(n: 3)
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 9 * startsOneEnds(n: n - 1)
}
func startsOneEndsWithOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsWithOne(n: n - 1)
}
func startsOneEndsWithZero(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsWithZero(n: n - 1)
}
func countNumbersWithSameConsecutiveDifferences(n: Int, k: Int) -> Int {
if n == 1 {
return 10
}
var count = 0
for i in 1...9 {
if i - k >= 0 && i - k < 10 {
count += startsOneEndsWithOne(n: n - 1)
}
if i + k >= 0 && i + k < 10 {
count += startsOneEndsWithZero(n: n - 1)
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 9 * startsOneEnds(n: n - 1)
}
func startsOneEndsWithOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsWithOne(n: n - 1)
}
func startsOneEndsWithZero(n: Int) -> Int {
if n == 1 {
return 1
}
return 9 * startsOneEndsWithZero(n: n - 1)
}
func countNumbersWithSameConsecutiveDifferences(n: Int, k: Int) -> Int {
if n == 1 {
return 10
}
var count = 0
for i in 1...9 {
if i - k >= 0 && i - k < 10 {
count += startsOneEndsWithOne(n: n - 1)
}
if i + k >= 0 && i + k < 10 {
count += startsOneEndsWithZero(n: n - 1)
}
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
return count * 10 + count - 1
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
return count * 10 + count - 1
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
var count = 0
for i in 1..<10 {
count += startsOneEnds(n: n-1)
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
var count = 0
for i in 1..<10 {
count += startsOneEnds(n: n-1)
}
return count
}
```
for i in 1..<10 { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
if n == 2 {
return 10
}
var count = 0
for i in 1...9 {
count += startsOneEnds(n: n - 1)
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
if n == 2 {
return 10
}
var count = 0
for i in 1...9 {
count += startsOneEnds(n: n - 1)
}
return count
}
```
for i in 1...9 { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func solve(N: Int) -> String {
return String(N, radix: 2).compactMap { $0.wholeNumberValue }.reduce(0, +).description
}
```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 {
return String(N, radix: 2).compactMap { $0.wholeNumberValue }.reduce(0, +).description
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var sum = 0
var n = N
while n > 0 {
sum += n % 2
n = n / 2
}
return String(sum)
}
```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 sum = 0
var n = N
while n > 0 {
sum += n % 2
n = n / 2
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
return String(N, radix: 2).reduce(0) { $0 + Int(String($1))! }
}
```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 {
return String(N, radix: 2).reduce(0) { $0 + Int(String($1))! }
}
```
return String(N, radix: 2).reduce(0) { $0 + Int(String($1))! } // cannot convert return expression of type 'Int' to return type 'String'
func solve(N: Int) -> String {
var sum = 0
var n = N
while n != 0 {
sum += n % 2
n /= 2
}
return String(sum)
}
```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 sum = 0
var n = N
while n != 0 {
sum += n % 2
n /= 2
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var sum = 0
var n = N
while n != 0 {
sum += n % 2
n /= 2
}
return String(sum)
}
```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 sum = 0
var n = N
while n != 0 {
sum += n % 2
n /= 2
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
return String(N, radix: 2)
}
```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 {
return String(N, radix: 2)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var sum = 0
var n = N
while n > 0 {
sum += n % 2
n /= 2
}
return String(sum)
}
```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 sum = 0
var n = N
while n > 0 {
sum += n % 2
n /= 2
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var sum = 0
var num = N
while num > 0 {
sum += num % 2
num /= 2
}
return String(sum)
}
```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 sum = 0
var num = N
while num > 0 {
sum += num % 2
num /= 2
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
return String(N, radix: 2).map{ String($0) }.reduce(0, { $0 + Int($1)! })
}
```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 {
return String(N, radix: 2).map{ String($0) }.reduce(0, { $0 + Int($1)! })
}
```
return String(N, radix: 2).map{ String($0) }.reduce(0, { $0 + Int($1)! }) // cannot convert return expression of type 'Int' to return type 'String'
func add(lst: [Int]) -> Int {
return lst.filter{ $0.isMultiple(of: 2) && $0.index % 2 != 0 }.reduce(0, +)
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter{ $0.isMultiple(of: 2) && $0.index % 2 != 0 }.reduce(0, +)
}
```
return lst.filter{ $0.isMultiple(of: 2) && $0.index % 2 != 0 }.reduce(0, +) // trailing closure passed to parameter of type 'Predicate<Int>' that does not accept a closure
func add(lst: [Int]) -> Int {
return lst.enumerated().filter({ $0.offset % 2 == 0 }).map({ $0.element }).reduce(0, +)
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.enumerated().filter({ $0.offset % 2 == 0 }).map({ $0.element }).reduce(0, +)
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 && lst.index(of: $0)! % 2 == 1 }.reduce(0, +)
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 && lst.index(of: $0)! % 2 == 1 }.reduce(0, +)
}
```
return lst.filter { $0 % 2 == 0 && lst.index(of: $0)! % 2 == 1 }.reduce(0, +) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 1 && $0.element % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 1 && $0.element % 2 == 0 }.map { $0.element }.reduce(0, +)
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 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 && value % 2 == 0 {
sum += value
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func antiShuffle(s: String) -> String {
if s.isEmpty { return s }
let words = s.components(separatedBy: " ")
return words.map { word in
word.characters.sorted(by: <).joined(separator: "")
}.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
if s.isEmpty { return s }
let words = s.components(separatedBy: " ")
return words.map { word in
word.characters.sorted(by: <).joined(separator: "")
}.joined(separator: " ")
}
```
word.characters.sorted(by: <).joined(separator: "") // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
let sorted = word.sorted { $0 < $1 }
result.append(String(sorted))
}
return result.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
let sorted = word.sorted { $0 < $1 }
result.append(String(sorted))
}
return result.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
// Write your code here
let words = s.split(separator: " ")
let sortedWords = words.map { word -> String in
let sortedCharacters = word.map { String($0) }.sorted { $0 < $1 }
return String(sortedCharacters.joined())
}
return sortedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
// Write your code here
let words = s.split(separator: " ")
let sortedWords = words.map { word -> String in
let sortedCharacters = word.map { String($0) }.sorted { $0 < $1 }
return String(sortedCharacters.joined())
}
return sortedWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords: [String] = []
for word in words {
var newWord: [Character] = []
for char in word {
newWord.append(char)
}
newWord.sort { $0 < $1 }
newWords.append(String(newWord))
}
return newWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords: [String] = []
for word in words {
var newWord: [Character] = []
for char in word {
newWord.append(char)
}
newWord.sort { $0 < $1 }
newWords.append(String(newWord))
}
return newWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
if s.isEmpty {
return ""
}
return s.components(separatedBy: " ").map {
$0.sorted()
}.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
if s.isEmpty {
return ""
}
return s.components(separatedBy: " ").map {
$0.sorted()
}.joined(separator: " ")
}
```
$0.sorted() // cannot convert value of type '[String.Element]' (aka 'Array<Character>') to closure result type 'String'
func antiShuffle(s: String) -> String {
// Write your code here
let words = s.components(separatedBy: " ")
var newWords: [String] = []
for word in words {
var newWord = ""
var characters = [Character](word)
characters.sort()
for char in characters {
newWord.append(char)
}
newWords.append(newWord)
}
return newWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
// Write your code here
let words = s.components(separatedBy: " ")
var newWords: [String] = []
for word in words {
var newWord = ""
var characters = [Character](word)
characters.sort()
for char in characters {
newWord.append(char)
}
newWords.append(newWord)
}
return newWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
if s.isEmpty { return s }
let words = s.components(separatedBy: " ")
let sortedWords = words.map { word in
let sortedChars = word.sorted { $0 < $1 }
return String(sortedChars)
}
return sortedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
if s.isEmpty { return s }
let words = s.components(separatedBy: " ")
let sortedWords = words.map { word in
let sortedChars = word.sorted { $0 < $1 }
return String(sortedChars)
}
return sortedWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
var result = ""
let words = s.components(separatedBy: " ")
for word in words {
var newWord = ""
for char in word {
newWord += String(char)
}
result += newWord + " "
}
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 = ""
let words = s.components(separatedBy: " ")
for word in words {
var newWord = ""
for char in word {
newWord += String(char)
}
result += newWord + " "
}
return result
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
if s.isEmpty { return s }
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
var sorted = Array(word)
sorted.sort()
result += String(sorted) + " "
}
return String(result.dropLast())
}
```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 {
if s.isEmpty { return s }
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
var sorted = Array(word)
sorted.sort()
result += String(sorted) + " "
}
return String(result.dropLast())
}
```
func antiShuffle(s: String) -> String {
var result = ""
let words = s.components(separatedBy: " ")
for word in words {
var sortedWord = ""
for char in word {
sortedWord.append(String(char).sorted().first!)
}
result.append(sortedWord)
result.append(" ")
}
result.removeLast()
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 = ""
let words = s.components(separatedBy: " ")
for word in words {
var sortedWord = ""
for char in word {
sortedWord.append(String(char).sorted().first!)
}
result.append(sortedWord)
result.append(" ")
}
result.removeLast()
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
let result = lst.enumerated().compactMap { (index, row) in
row.enumerated().compactMap { (colIndex, value) in
if value == x {
return (index, colIndex)
} else {
return nil
}
}
}
let sorted = result.sorted { $0.0 < $1.0 }
return sorted.map { $0.sorted { $0.1 > $1.1 } }
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
let result = lst.enumerated().compactMap { (index, row) in
row.enumerated().compactMap { (colIndex, value) in
if value == x {
return (index, colIndex)
} else {
return nil
}
}
}
let sorted = result.sorted { $0.0 < $1.0 }
return sorted.map { $0.sorted { $0.1 > $1.1 } }
}
```
let sorted = result.sorted { $0.0 < $1.0 } // cannot infer type of closure parameter '$0' without a type annotation
let sorted = result.sorted { $0.0 < $1.0 } // cannot infer type of closure parameter '$1' without a type annotation
let sorted = result.sorted { $0.0 < $1.0 } // type '(_, _) -> Bool' cannot conform to 'SortComparator'
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)] = []
var index = 0
for (i, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort {
if $0.0 != $1.0 {
return $0.0 < $1.0
} else {
return $0.1 > $1.1
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
var index = 0
for (i, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort {
if $0.0 != $1.0 {
return $0.0 < $1.0
} else {
return $0.1 > $1.1
}
}
return result
}
```
var index = 0 // initialization of variable 'index' was never used; consider replacing with assignment to '_' or removing it
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, value) in lst.enumerated() {
if let index = value.firstIndex(of: x) {
result.append((index, value.count - 1 - index))
}
}
return result.sorted {
if $0.0 == $1.0 {
return $0.1 > $1.1
}
return $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, value) in lst.enumerated() {
if let index = value.firstIndex(of: x) {
result.append((index, value.count - 1 - index))
}
}
return result.sorted {
if $0.0 == $1.0 {
return $0.1 > $1.1
}
return $0.0 < $1.0
}
}
```
for (index, value) in lst.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
var row = 0
for i in lst {
if i.contains(x) {
if let index = i.lastIndex(of: x) {
result.append((row, index))
}
}
row += 1
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
var row = 0
for i in lst {
if i.contains(x) {
if let index = i.lastIndex(of: x) {
result.append((row, index))
}
}
row += 1
}
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.enumerated().filter { $1.contains(x) }
.map { (row, col) -> (Int, Int) in
let index = col.firstIndex(of: x)!
return (row, col.count - 1 - index)
}
}
```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 lst.enumerated().filter { $1.contains(x) }
.map { (row, col) -> (Int, Int) in
let index = col.firstIndex(of: x)!
return (row, col.count - 1 - index)
}
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.enumerated().flatMap { (idx, row) in
row.enumerated().compactMap { (idx2, value) in
value == x ? (idx, idx2) : nil
}
}
}
```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 lst.enumerated().flatMap { (idx, row) in
row.enumerated().compactMap { (idx2, value) in
value == x ? (idx, idx2) : nil
}
}
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.enumerated().compactMap { (idx, row) in
row.enumerated().compactMap { (idx, value) in
value == x ? (idx, idx) : nil
}
}.flatMap { $0 }.sorted(by: { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.1) })
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.enumerated().compactMap { (idx, row) in
row.enumerated().compactMap { (idx, value) in
value == x ? (idx, idx) : nil
}
}.flatMap { $0 }.sorted(by: { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.1) })
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.enumerated().filter { $1.contains(x) }.flatMap { (row, arr) in
arr.enumerated().filter { $1 == x }.map { (row, $0) }
}.sorted { $0.0 == $1.0 ? $0.1 > $1.1 : $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)] {
return lst.enumerated().filter { $1.contains(x) }.flatMap { (row, arr) in
arr.enumerated().filter { $1 == x }.map { (row, $0) }
}.sorted { $0.0 == $1.0 ? $0.1 > $1.1 : $0.0 < $1.0 }
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.enumerated().compactMap { (idx, row) in
row.enumerated().compactMap { (colIdx, col) in
col == x ? (idx, colIdx) : nil
}
}.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)] {
return lst.enumerated().compactMap { (idx, row) in
row.enumerated().compactMap { (colIdx, col) in
col == x ? (idx, colIdx) : nil
}
}.sorted { $0[0] < $1[0] }
}
```
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] {
// 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] {
guard array.count > 1 else { return array }
let sum = array.first! + array.last!
let sortedArray = sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
return sortedArray
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.first! + array.last!
let sortedArray = sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
return sortedArray
}
```
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else {
return array
}
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted()
}
```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] {
guard array.count > 1 else {
return array
}
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted()
}
```
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.reduce(0, +)
let isSumEven = sum % 2 == 0
let sortedArray = isSumEven ? array.sorted(by: >) : array.sorted()
return sortedArray
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.reduce(0, +)
let isSumEven = sum % 2 == 0
let sortedArray = isSumEven ? array.sorted(by: >) : array.sorted()
return sortedArray
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.first! + array.last!
let sortedArray = sum % 2 == 0 ? array.sorted(by: >) : array.sorted()
return sortedArray
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.first! + array.last!
let sortedArray = sum % 2 == 0 ? array.sorted(by: >) : array.sorted()
return sortedArray
}
```
func sortArray(array: [Int]) -> [Int] {
var arr = array
if arr.count == 0 || arr.count == 1 {
return arr
}
let sum = arr.first! + arr.last!
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort()
}
return arr
}
```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 arr = array
if arr.count == 0 || arr.count == 1 {
return arr
}
let sum = arr.first! + arr.last!
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort()
}
return arr
}
```
func sortArray(array: [Int]) -> [Int] {
var sortedArray = array
let sum = sortedArray.first! + sortedArray.last!
if sum % 2 == 0 {
sortedArray.sort { $0 < $1 }
} else {
sortedArray.sort { $0 > $1 }
}
return sortedArray
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var sortedArray = array
let sum = sortedArray.first! + sortedArray.last!
if sum % 2 == 0 {
sortedArray.sort { $0 < $1 }
} else {
sortedArray.sort { $0 > $1 }
}
return sortedArray
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func sortArray(array: [Int]) -> [Int] {
// write your code here
if array.count <= 1 {
return array
}
let sum = array.first! + array.last!
var result = array
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] {
// write your code here
if array.count <= 1 {
return array
}
let sum = array.first! + array.last!
var result = array
if sum % 2 == 0 {
result.sort(by: >)
} else {
result.sort(by: <)
}
return result
}
```
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.first! + array.last!
if sum % 2 == 0 {
array.sort(by: >)
} else {
array.sort(by: <)
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.first! + array.last!
if sum % 2 == 0 {
array.sort(by: >)
} else {
array.sort(by: <)
}
return array
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let encryptedAlphabet = alphabet.dropFirst(2) + alphabet.dropLast(2)
return s.map { encryptedAlphabet[$0.unicodeScalars.firstIndex(of: $0)!] }.joined()
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let encryptedAlphabet = alphabet.dropFirst(2) + alphabet.dropLast(2)
return s.map { encryptedAlphabet[$0.unicodeScalars.firstIndex(of: $0)!] }.joined()
}
```
return s.map { encryptedAlphabet[$0.unicodeScalars.firstIndex(of: $0)!] }.joined() // subscript 'subscript(_:)' requires that 'String.UnicodeScalarView.Index' (aka 'String.Index') conform to 'RangeExpression'
return s.map { encryptedAlphabet[$0.unicodeScalars.firstIndex(of: $0)!] }.joined() // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String.UnicodeScalarView.Element' (aka 'Unicode.Scalar')
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var newString = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 4
newString += String(alphabet[newIndex])
}
}
return newString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var newString = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = index + 4
newString += String(alphabet[newIndex])
}
}
return newString
}
```
let newIndex = index + 4 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let alphabetArray = Array(alphabet)
let sArray = Array(s)
var newString = ""
for char in sArray {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = alphabetArray.index(charIndex!, offsetBy: 4)
let newChar = alphabetArray[newIndex]
newString.append(newChar)
}
return newString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let alphabetArray = Array(alphabet)
let sArray = Array(s)
var newString = ""
for char in sArray {
let charIndex = alphabet.firstIndex(of: char)
let newIndex = alphabetArray.index(charIndex!, offsetBy: 4)
let newChar = alphabetArray[newIndex]
newString.append(newChar)
}
return newString
}
```
let newIndex = alphabetArray.index(charIndex!, offsetBy: 4) // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for letter in s {
let index = alphabet.firstIndex(of: letter)
if let index = index {
let newIndex = index + 4
let newLetter = alphabet[newIndex]
encryptedString.append(newLetter)
}
}
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 {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for letter in s {
let index = alphabet.firstIndex(of: letter)
if let index = index {
let newIndex = index + 4
let newLetter = alphabet[newIndex]
encryptedString.append(newLetter)
}
}
return encryptedString
}
```
let newIndex = index + 4 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var newString = ""
for letter in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: letter.unicodeScalars.first!.value - 97)
let newIndex = alphabet.index(index, offsetBy: 4)
newString.append(alphabet[newIndex])
}
return newString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var newString = ""
for letter in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: letter.unicodeScalars.first!.value - 97)
let newIndex = alphabet.index(index, offsetBy: 4)
newString.append(alphabet[newIndex])
}
return newString
}
```
let index = alphabet.index(alphabet.startIndex, offsetBy: letter.unicodeScalars.first!.value - 97) // 'index(_:offsetBy:)' is unavailable: all index distances are now of type Int
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let alphabetArray = Array(alphabet)
var encryptedArray = [Character]()
for char in s {
if let index = alphabetArray.firstIndex(of: char) {
let newIndex = index + 2 * 2
if newIndex > 25 {
encryptedArray.append(alphabetArray[newIndex - 26])
} else {
encryptedArray.append(alphabetArray[newIndex])
}
}
}
return String(encryptedArray)
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let alphabetArray = Array(alphabet)
var encryptedArray = [Character]()
for char in s {
if let index = alphabetArray.firstIndex(of: char) {
let newIndex = index + 2 * 2
if newIndex > 25 {
encryptedArray.append(alphabetArray[newIndex - 26])
} else {
encryptedArray.append(alphabetArray[newIndex])
}
}
}
return String(encryptedArray)
}
```
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for letter in s {
if let index = alphabet.index(of: letter) {
let newIndex = alphabet.index(index, offsetBy: 4)
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 {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for letter in s {
if let index = alphabet.index(of: letter) {
let newIndex = alphabet.index(index, offsetBy: 4)
encrypted.append(alphabet[newIndex])
}
}
return encrypted
}
```
if let index = alphabet.index(of: letter) { // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// Fatal error: String index is out of bounds
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = alphabet.index(index, offsetBy: 4)
let newLetter = alphabet[newIndex]
encrypted.append(newLetter)
}
}
return encrypted
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for letter in s {
if let index = alphabet.firstIndex(of: letter) {
let newIndex = alphabet.index(index, offsetBy: 4)
let newLetter = alphabet[newIndex]
encrypted.append(newLetter)
}
}
return encrypted
}
```
// Fatal error: String index is out of bounds
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = alphabet.index(index, offsetBy: 4)
encryptedString.append(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 {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
if let index = alphabet.firstIndex(of: char) {
let newIndex = alphabet.index(index, offsetBy: 4)
encryptedString.append(alphabet[newIndex])
}
}
return encryptedString
}
```
// Fatal error: String index is out of bounds
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for letter in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: alphabet.distance(from: alphabet.startIndex, to: alphabet.firstIndex(of: letter)!))
let newIndex = alphabet.index(index, offsetBy: 2 * 2)
if newIndex < alphabet.endIndex {
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[alphabet.index(alphabet.startIndex, offsetBy: alphabet.distance(from: alphabet.startIndex, to: newIndex) - alphabet.count)])
}
}
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 {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for letter in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: alphabet.distance(from: alphabet.startIndex, to: alphabet.firstIndex(of: letter)!))
let newIndex = alphabet.index(index, offsetBy: 2 * 2)
if newIndex < alphabet.endIndex {
encryptedString.append(alphabet[newIndex])
} else {
encryptedString.append(alphabet[alphabet.index(alphabet.startIndex, offsetBy: alphabet.distance(from: alphabet.startIndex, to: newIndex) - alphabet.count)])
}
}
return encryptedString
}
```
// Fatal error: String index is out of bounds
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
guard let secondSmallest = sorted.first(where: { $0 != sorted[0] }) else { return nil }
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 }
let sorted = lst.sorted()
guard let secondSmallest = sorted.first(where: { $0 != sorted[0] }) else { return nil }
return secondSmallest
}
```
func nextSmallest(lst: [Int]) -> Int? {
var sortedLst = lst.sorted()
if sortedLst.count <= 1 {
return nil
}
return sortedLst[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 sortedLst = lst.sorted()
if sortedLst.count <= 1 {
return nil
}
return sortedLst[1]
}
```
var sortedLst = lst.sorted() // variable 'sortedLst' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
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? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
return sorted[1]
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
let sorted = lst.sorted()
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? {
if lst.count < 2 {
return nil
}
let sorted = lst.sorted()
return sorted[1]
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var sortedArray = lst.sorted()
let smallest = sortedArray.first!
let secondSmallest = sortedArray[1]
let index = lst.firstIndex(of: secondSmallest)
if lst.count < 2 || lst.count == 2 && lst.first == lst.last {
return nil
}
return lst[index!]
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
var sortedArray = lst.sorted()
let smallest = sortedArray.first!
let secondSmallest = sortedArray[1]
let index = lst.firstIndex(of: secondSmallest)
if lst.count < 2 || lst.count == 2 && lst.first == lst.last {
return nil
}
return lst[index!]
}
```
var sortedArray = lst.sorted() // variable 'sortedArray' was never mutated; consider changing to 'let' constant
let smallest = sortedArray.first! // initialization of immutable value 'smallest' was never used; consider replacing with assignment to '_' or removing it
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func nextSmallest(lst: [Int]) -> Int? {
var sorted = lst.sorted()
guard let second = sorted.first(where: { $0 > sorted.first!}) else { return nil }
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? {
var sorted = lst.sorted()
guard let second = sorted.first(where: { $0 > sorted.first!}) else { return nil }
return second
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func nextSmallest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var sortedArray = lst.sorted()
for i in 0..<sortedArray.count {
if sortedArray[i] == sortedArray[i+1] {
sortedArray.remove(at: i)
}
}
return sortedArray[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? {
if lst.count < 2 {
return nil
}
var sortedArray = lst.sorted()
for i in 0..<sortedArray.count {
if sortedArray[i] == sortedArray[i+1] {
sortedArray.remove(at: i)
}
}
return sortedArray[1]
}
```
// Fatal error: Index out of range
func nextSmallest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var smallest = Int.max
var secondSmallest = Int.max
for i in lst {
if i < smallest {
secondSmallest = smallest
smallest = i
} else if i < secondSmallest {
secondSmallest = i
}
}
return secondSmallest == Int.max ? nil : 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? {
if lst.count < 2 {
return nil
}
var smallest = Int.max
var secondSmallest = Int.max
for i in lst {
if i < smallest {
secondSmallest = smallest
smallest = i
} else if i < secondSmallest {
secondSmallest = i
}
}
return secondSmallest == Int.max ? nil : secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var sortedList = lst.sorted()
var secondSmallest = sortedList[1]
for i in 0...sortedList.count - 2 {
if sortedList[i] == secondSmallest {
secondSmallest = sortedList[i + 1]
}
}
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? {
if lst.count < 2 {
return nil
}
var sortedList = lst.sorted()
var secondSmallest = sortedList[1]
for i in 0...sortedList.count - 2 {
if sortedList[i] == secondSmallest {
secondSmallest = sortedList[i + 1]
}
}
return secondSmallest
}
```
var sortedList = lst.sorted() // variable 'sortedList' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var sortedList = lst
sortedList.sort()
var smallest = sortedList[0]
var secondSmallest = sortedList[1]
for i in 1..<sortedList.count {
if sortedList[i] > smallest && sortedList[i] < secondSmallest {
secondSmallest = sortedList[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? {
var sortedList = lst
sortedList.sort()
var smallest = sortedList[0]
var secondSmallest = sortedList[1]
for i in 1..<sortedList.count {
if sortedList[i] > smallest && sortedList[i] < secondSmallest {
secondSmallest = sortedList[i]
}
}
return secondSmallest
}
```
var smallest = sortedList[0] // variable 'smallest' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func isBored(S: String) -> Int {
return S.componentsSeparatedByString(".").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString }.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 {
return S.componentsSeparatedByString(".").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString }.filter { $0.hasPrefix("i") }.count
}
```
return S.componentsSeparatedByString(".").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString }.filter { $0.hasPrefix("i") }.count // cannot call value of non-function type 'CharacterSet'
return S.componentsSeparatedByString(".").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString }.filter { $0.hasPrefix("i") }.count // value of type 'String' has no member 'componentsSeparatedByString'
func isBored(S: String) -> Int {
// your code here
let words = S.componentsSeparatedByString(" ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
// your code here
let words = S.componentsSeparatedByString(" ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
let words = S.componentsSeparatedByString(" ") // value of type 'String' has no member 'componentsSeparatedByString'
func isBored(S: String) -> Int {
return S.componentsSeparatedByString(".").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 {
return S.componentsSeparatedByString(".").filter({ $0.hasPrefix("I") }).count
}
```
return S.componentsSeparatedByString(".").filter({ $0.hasPrefix("I") }).count // value of type 'String' has no member 'componentsSeparatedByString'
func isBored(S: String) -> Int {
var count = 0
let sentences = S.components(separatedBy: ".!?")
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
let sentences = S.components(separatedBy: ".!?")
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var count = 0
let words = S.split(separator: " ")
for (index, word) in words.enumerated() {
if word == "I" {
if index != 0 && words[index - 1] != "." && words[index - 1] != "?" && words[index - 1] != "!" {
count += 1
}
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
let words = S.split(separator: " ")
for (index, word) in words.enumerated() {
if word == "I" {
if index != 0 && words[index - 1] != "." && words[index - 1] != "?" && words[index - 1] != "!" {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var count = 0
let words = S.split(separator: " ")
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
let words = S.split(separator: " ")
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: "I").count - 1
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
return S.components(separatedBy: "I").count - 1
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let sentences = S.components(separatedBy: ["?", ".", "!"])
let boredSentences = sentences.filter { $0.hasPrefix("I") }
return boredSentences.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 sentences = S.components(separatedBy: ["?", ".", "!"])
let boredSentences = sentences.filter { $0.hasPrefix("I") }
return boredSentences.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: " ").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 {
return S.components(separatedBy: " ").filter { $0.lowercased().hasPrefix("i") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var count = 0
let words = S.split(separator: " ")
for i in 0..<words.count {
if words[i] == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
let words = S.split(separator: " ")
for i in 0..<words.count {
if words[i] == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
let sum2 = x + z
let sum3 = y + z
return x.isInteger && y.isInteger && z.isInteger && (sum == z || sum2 == y || sum3 == x)
}
```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 {
let sum = x + y
let sum2 = x + z
let sum3 = y + z
return x.isInteger && y.isInteger && z.isInteger && (sum == z || sum2 == y || sum3 == x)
}
```
return x.isInteger && y.isInteger && z.isInteger && (sum == z || sum2 == y || sum3 == x) // value of type 'Double' has no member 'isInteger'
return x.isInteger && y.isInteger && z.isInteger && (sum == z || sum2 == y || sum3 == x) // value of type 'Double' has no member 'isInteger'
return x.isInteger && y.isInteger && z.isInteger && (sum == z || sum2 == y || sum3 == x) // value of type 'Double' has no member 'isInteger'
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 {
let sum = x + y
return sum == z ? true : 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 {
let sum = x + y
return sum == z ? true : false
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x + y == z || x + z == y || y + z == x) && x.isInteger && y.isInteger && z.isInteger
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x + y == z || x + z == y || y + z == x) && x.isInteger && y.isInteger && z.isInteger
}
// extension Double {
// var isInteger: Bool {
// return trunc(self) == self
// }
// }
```
return (x + y == z || x + z == y || y + z == x) && x.isInteger && y.isInteger && z.isInteger // value of type 'Double' has no member 'isInteger'
return (x + y == z || x + z == y || y + z == x) && x.isInteger && y.isInteger && z.isInteger // value of type 'Double' has no member 'isInteger'
return (x + y == z || x + z == y || y + z == x) && x.isInteger && y.isInteger && z.isInteger // value of type 'Double' has no member 'isInteger'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
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 == y + z || y == x + z || z == x + y {
return true
}
return false
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x + y == z) || (x + z == y) || (y + z == x)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x + y == z) || (x + z == y) || (y + z == x)
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
let sum1 = y + z
let sum2 = x + z
if x == sum || y == sum1 || z == sum2 {
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 {
let sum = x + y
let sum1 = y + z
let sum2 = x + z
if x == sum || y == sum1 || z == sum2 {
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 anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if sum == z {
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 {
let sum = x + y
if sum == z {
return true
}
else {
return false
}
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
var newMessage = ""
for char in newString {
if char.isLetter {
var newChar = char
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
newChar = String(char).uppercased()
}
newMessage += newChar
} else {
newMessage += char
}
}
return newMessage
}
```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 newString = ""
for char in message {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
var newMessage = ""
for char in newString {
if char.isLetter {
var newChar = char
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
newChar = String(char).uppercased()
}
newMessage += newChar
} else {
newMessage += char
}
}
return newMessage
}
```
newChar = String(char).uppercased() // cannot assign value of type 'String' to type 'Character'
newMessage += newChar // cannot convert value of type 'Character' to expected argument type 'String'
newMessage += char // cannot convert value of type 'Character' to expected argument type 'String'
func encode(message: String) -> String {
let vowels = "aeiouAEIOU"
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var encodedMessage = ""
for char in message {
if vowels.contains(char) {
let index = vowels.index(of: char)
let newIndex = index! + 2
encodedMessage += String(alphabet[newIndex])
} else {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
}
}
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 {
let vowels = "aeiouAEIOU"
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var encodedMessage = ""
for char in message {
if vowels.contains(char) {
let index = vowels.index(of: char)
let newIndex = index! + 2
encodedMessage += String(alphabet[newIndex])
} else {
if char.isUppercase {
encodedMessage += String(char).lowercased()
} else {
encodedMessage += String(char).uppercased()
}
}
}
return encodedMessage
}
```
let index = vowels.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
let newIndex = index! + 2 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encode(message: String) -> String {
let vowels: [Character] = ["a","e","i","o","u"]
let alphabet: [Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var newMessage = ""
for char in message {
if vowels.contains(char) {
if char == "a" {
newMessage += "c"
} else if char == "e" {
newMessage += "g"
} else if char == "i" {
newMessage += "k"
} else if char == "o" {
newMessage += "q"
} else if char == "u" {
newMessage += "y"
}
} else {
if char == char.uppercased() {
newMessage += String(char).lowercased()
} else {
newMessage += String(char).uppercased()
}
}
}
return newMessage
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels: [Character] = ["a","e","i","o","u"]
let alphabet: [Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var newMessage = ""
for char in message {
if vowels.contains(char) {
if char == "a" {
newMessage += "c"
} else if char == "e" {
newMessage += "g"
} else if char == "i" {
newMessage += "k"
} else if char == "o" {
newMessage += "q"
} else if char == "u" {
newMessage += "y"
}
} else {
if char == char.uppercased() {
newMessage += String(char).lowercased()
} else {
newMessage += String(char).uppercased()
}
}
}
return newMessage
}
```
if char == char.uppercased() { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func encode(message: String) -> String {
let vowels: [Character] = ["a","e","i","o","u"]
let alphabet: [Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var newString = ""
for char in message {
if vowels.contains(char) {
let index = vowels.firstIndex(of: char)!
newString += String(alphabet[index+2])
} else {
newString += String(char)
}
}
var newString2 = ""
for char in newString {
if char.isLetter {
if char.isUppercase {
newString2 += String(char).lowercased()
} else {
newString2 += String(char).uppercased()
}
} else {
newString2 += String(char)
}
}
return newString2
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels: [Character] = ["a","e","i","o","u"]
let alphabet: [Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var newString = ""
for char in message {
if vowels.contains(char) {
let index = vowels.firstIndex(of: char)!
newString += String(alphabet[index+2])
} else {
newString += String(char)
}
}
var newString2 = ""
for char in newString {
if char.isLetter {
if char.isUppercase {
newString2 += String(char).lowercased()
} else {
newString2 += String(char).uppercased()
}
} else {
newString2 += String(char)
}
}
return newString2
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
let vowels: [Character] = ["a","e","i","o","u"]
var newString = ""
for char in message {
if vowels.contains(char) {
let index = vowels.firstIndex(of: char)!
let newChar = vowels[index + 2]
newString.append(newChar)
} else {
let newChar = char.lowercased()
newString.append(newChar)
}
}
return newString
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels: [Character] = ["a","e","i","o","u"]
var newString = ""
for char in message {
if vowels.contains(char) {
let index = vowels.firstIndex(of: char)!
let newChar = vowels[index + 2]
newString.append(newChar)
} else {
let newChar = char.lowercased()
newString.append(newChar)
}
}
return newString
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var encodedMessage = ""
let vowels = "aeiouAEIOU"
for char in message {
let charString = String(char)
if charString.rangeOfCharacter(from: CharacterSet.uppercaseLetters) != nil {
encodedMessage += charString.lowercased()
} else if charString.rangeOfCharacter(from: CharacterSet.lowercaseLetters) != nil {
encodedMessage += charString.uppercased()
} else if vowels.contains(charString) {
let index = vowels.index(vowels.startIndex, offsetBy: 2)
let newChar = vowels[index]
encodedMessage += String(newChar)
} else {
encodedMessage += charString
}
}
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 = ""
let vowels = "aeiouAEIOU"
for char in message {
let charString = String(char)
if charString.rangeOfCharacter(from: CharacterSet.uppercaseLetters) != nil {
encodedMessage += charString.lowercased()
} else if charString.rangeOfCharacter(from: CharacterSet.lowercaseLetters) != nil {
encodedMessage += charString.uppercased()
} else if vowels.contains(charString) {
let index = vowels.index(vowels.startIndex, offsetBy: 2)
let newChar = vowels[index]
encodedMessage += String(newChar)
} else {
encodedMessage += charString
}
}
return encodedMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
let vowels: [Character] = ["a", "e", "i", "o", "u"]
var newString = ""
for char in message {
if char.isLetter {
if vowels.contains(char.lowercased().first!) {
newString.append(char.uppercased())
} else {
newString.append(char.lowercased())
}
} else {
newString.append(char)
}
}
var newString2 = ""
for char in newString {
if char.isLetter {
if char.isUppercase {
newString2.append(char.lowercased())
} else {
newString2.append(char.uppercased())
}
} else {
newString2.append(char)
}
}
return newString2
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels: [Character] = ["a", "e", "i", "o", "u"]
var newString = ""
for char in message {
if char.isLetter {
if vowels.contains(char.lowercased().first!) {
newString.append(char.uppercased())
} else {
newString.append(char.lowercased())
}
} else {
newString.append(char)
}
}
var newString2 = ""
for char in newString {
if char.isLetter {
if char.isUppercase {
newString2.append(char.lowercased())
} else {
newString2.append(char.uppercased())
}
} else {
newString2.append(char)
}
}
return newString2
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
let vowels = "aeiou"
var newString = ""
for char in message {
if char.isLetter {
if vowels.contains(char) {
let index = vowels.firstIndex(of: char)!
let newIndex = index.encodedOffset + 2
newString += String(vowels[vowels.index(vowels.startIndex, offsetBy: newIndex)])
} else {
newString += String(char).uppercased()
}
} else {
newString += String(char)
}
}
return newString
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels = "aeiou"
var newString = ""
for char in message {
if char.isLetter {
if vowels.contains(char) {
let index = vowels.firstIndex(of: char)!
let newIndex = index.encodedOffset + 2
newString += String(vowels[vowels.index(vowels.startIndex, offsetBy: newIndex)])
} else {
newString += String(char).uppercased()
}
} else {
newString += String(char)
}
}
return newString
}
```
let newIndex = index.encodedOffset + 2 // 'encodedOffset' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.
// XCTAssertTrue failed
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
newMessage.append(String(char).uppercased())
} else {
newMessage.append(String(char).lowercased())
}
}
return newMessage
}
```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 newMessage = ""
for char in message {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
newMessage.append(String(char).uppercased())
} else {
newMessage.append(String(char).lowercased())
}
}
return newMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var encodedMessage = ""
for letter in message {
if letter.isLetter {
if vowels.contains(String(letter).lowercased()) {
switch String(letter).lowercased() {
case "a":
encodedMessage.append("c")
case "e":
encodedMessage.append("g")
case "i":
encodedMessage.append("k")
case "o":
encodedMessage.append("q")
case "u":
encodedMessage.append("y")
default:
encodedMessage.append(letter)
}
} else {
encodedMessage.append(letter)
}
} else {
encodedMessage.append(letter)
}
}
return encodedMessage.capitalized
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var encodedMessage = ""
for letter in message {
if letter.isLetter {
if vowels.contains(String(letter).lowercased()) {
switch String(letter).lowercased() {
case "a":
encodedMessage.append("c")
case "e":
encodedMessage.append("g")
case "i":
encodedMessage.append("k")
case "o":
encodedMessage.append("q")
case "u":
encodedMessage.append("y")
default:
encodedMessage.append(letter)
}
} else {
encodedMessage.append(letter)
}
} else {
encodedMessage.append(letter)
}
}
return encodedMessage.capitalized
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2...Int(sqrt(Double(i))) {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime && i > maxPrime {
maxPrime = i
}
}
}
return maxPrime == 0 ? 0 : maxPrime.description.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 maxPrime = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2...Int(sqrt(Double(i))) {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime && i > maxPrime {
maxPrime = i
}
}
}
return maxPrime == 0 ? 0 : maxPrime.description.reduce(0, +)
}
```
return maxPrime == 0 ? 0 : maxPrime.description.reduce(0, +) // cannot convert value of type '(Int) -> Int' to expected argument type '(Int, String.Element) throws -> Int' (aka '(Int, Character) throws -> Int')
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
if num > maxPrime {
maxPrime = num
}
}
var prime = maxPrime
while prime > 1 {
if prime % 2 == 0 {
prime = prime / 2
} else {
prime = prime * 3 + 1
}
}
var sum = 0
while prime > 0 {
sum += prime % 10
prime /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
if num > maxPrime {
maxPrime = num
}
}
var prime = maxPrime
while prime > 1 {
if prime % 2 == 0 {
prime = prime / 2
} else {
prime = prime * 3 + 1
}
}
var sum = 0
while prime > 0 {
sum += prime % 10
prime /= 10
}
return sum
}
```
var maxPrimeDigitsSum = 0 // initialization of variable 'maxPrimeDigitsSum' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
var isPrime = true
if num <= 1 {
isPrime = false
} else if num <= 3 {
isPrime = true
} else if num % 2 == 0 || num % 3 == 0 {
isPrime = false
} else {
var i = 5
while i * i <= num {
if num % i == 0 || num % (i + 2) == 0 {
isPrime = false
break
}
i += 6
}
}
if isPrime && num > maxPrime {
maxPrime = num
maxPrimeDigitsSum = 0
while num > 0 {
maxPrimeDigitsSum += num % 10
num /= 10
}
}
}
return maxPrimeDigitsSum
}
```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 maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
var isPrime = true
if num <= 1 {
isPrime = false
} else if num <= 3 {
isPrime = true
} else if num % 2 == 0 || num % 3 == 0 {
isPrime = false
} else {
var i = 5
while i * i <= num {
if num % i == 0 || num % (i + 2) == 0 {
isPrime = false
break
}
i += 6
}
}
if isPrime && num > maxPrime {
maxPrime = num
maxPrimeDigitsSum = 0
while num > 0 {
maxPrimeDigitsSum += num % 10
num /= 10
}
}
}
return maxPrimeDigitsSum
}
```
num /= 10 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
func skjkasdkd(lst: [Int]) -> Int {
var prime = 0
var sum = 0
var isPrime = true
for i in lst {
if i < 2 {
continue
}
for j in 2...i-1 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
prime = i
sum += prime
}
isPrime = true
}
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 prime = 0
var sum = 0
var isPrime = true
for i in lst {
if i < 2 {
continue
}
for j in 2...i-1 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
prime = i
sum += prime
}
isPrime = true
}
return sum
}
```
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var prime: Int = 0
for i in lst {
if i.isMultiple(of: 2) == false && i.isMultiple(of: 3) == false && i.isMultiple(of: 5) == false && i.isMultiple(of: 7) == false && i.isMultiple(of: 11) == false && i.isMultiple(of: 13) == false && i.isMultiple(of: 17) == false && i.isMultiple(of: 19) == false {
prime = i
break
}
}
var sum: Int = 0
while prime != 0 {
sum += prime % 10
prime /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var prime: Int = 0
for i in lst {
if i.isMultiple(of: 2) == false && i.isMultiple(of: 3) == false && i.isMultiple(of: 5) == false && i.isMultiple(of: 7) == false && i.isMultiple(of: 11) == false && i.isMultiple(of: 13) == false && i.isMultiple(of: 17) == false && i.isMultiple(of: 19) == false {
prime = i
break
}
}
var sum: Int = 0
while prime != 0 {
sum += prime % 10
prime /= 10
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var sum = 0
for num in lst {
if num == 0 || num == 1 { continue }
if isPrime(num: num) {
if num > maxPrime {
maxPrime = num
}
}
}
for char in String(maxPrime) {
sum += Int(String(char))!
}
return sum
}
func isPrime(num: Int) -> Bool {
if num <= 1 { return false }
var i = 2
while i * i <= num {
if num % i == 0 {
return false
}
i += 1
}
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 maxPrime = 0
var sum = 0
for num in lst {
if num == 0 || num == 1 { continue }
if isPrime(num: num) {
if num > maxPrime {
maxPrime = num
}
}
}
for char in String(maxPrime) {
sum += Int(String(char))!
}
return sum
}
func isPrime(num: Int) -> Bool {
if num <= 1 { return false }
var i = 2
while i * i <= num {
if num % i == 0 {
return false
}
i += 1
}
return true
}
```
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
var sum = 0
for num in lst {
if num > largestPrime {
largestPrime = num
}
}
var largestPrimeString = "\(largestPrime)"
for char in largestPrimeString {
let intChar = Int(String(char))!
sum += intChar
}
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 largestPrime = 0
var sum = 0
for num in lst {
if num > largestPrime {
largestPrime = num
}
}
var largestPrimeString = "\(largestPrime)"
for char in largestPrimeString {
let intChar = Int(String(char))!
sum += intChar
}
return sum
}
```
var largestPrimeString = "\(largestPrime)" // variable 'largestPrimeString' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for num in lst {
if num > largestPrime && isPrime(num) {
largestPrime = num
}
}
return sumOfDigits(largestPrime)
}
func isPrime(_ num: Int) -> Bool {
if num <= 1 { return false }
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(_ num: Int) -> Int {
var sum = 0
var num = num
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for num in lst {
if num > largestPrime && isPrime(num) {
largestPrime = num
}
}
return sumOfDigits(largestPrime)
}
func isPrime(_ num: Int) -> Bool {
if num <= 1 { return false }
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(_ num: Int) -> Int {
var sum = 0
var num = num
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
if num > maxPrime && isPrime(num: num) {
maxPrime = num
maxPrimeDigitsSum = sumDigits(num: num)
}
}
return maxPrimeDigitsSum
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumDigits(num: Int) -> Int {
var sum = 0
var num = num
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
if num > maxPrime && isPrime(num: num) {
maxPrime = num
maxPrimeDigitsSum = sumDigits(num: num)
}
}
return maxPrimeDigitsSum
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumDigits(num: Int) -> Int {
var sum = 0
var num = num
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
var isPrime = true
if num <= 1 {
isPrime = false
} else if num <= 3 {
isPrime = true
} else if num % 2 == 0 || num % 3 == 0 {
isPrime = false
} else {
var i = 5
while i * i <= num {
if num % i == 0 || num % (i + 2) == 0 {
isPrime = false
break
}
i += 6
}
}
if isPrime {
let digitsSum = String(num).reduce(0) { $0 + Int(String($1))! }
if digitsSum > maxPrimeDigitsSum {
maxPrimeDigitsSum = digitsSum
maxPrime = num
}
}
}
return maxPrimeDigitsSum
}
```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 maxPrime = 0
var maxPrimeDigitsSum = 0
for num in lst {
var isPrime = true
if num <= 1 {
isPrime = false
} else if num <= 3 {
isPrime = true
} else if num % 2 == 0 || num % 3 == 0 {
isPrime = false
} else {
var i = 5
while i * i <= num {
if num % i == 0 || num % (i + 2) == 0 {
isPrime = false
break
}
i += 6
}
}
if isPrime {
let digitsSum = String(num).reduce(0) { $0 + Int(String($1))! }
if digitsSum > maxPrimeDigitsSum {
maxPrimeDigitsSum = digitsSum
maxPrime = num
}
}
}
return maxPrimeDigitsSum
}
```
var maxPrime = 0 // variable 'maxPrime' was written to, but never read
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2...n {
if i.isPrime() {
primes.append(i)
}
}
return primes
}
```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]()
for i in 2...n {
if i.isPrime() {
primes.append(i)
}
}
return primes
}
```
if i.isPrime() { // value of type 'Int' has no member 'isPrime'
func countUpTo(n: Int) -> [Int] {
var primes: [Int] = []
for i in 2..<n {
if isPrime(i) {
primes.append(i)
}
}
return primes
}
```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] = []
for i in 2..<n {
if isPrime(i) {
primes.append(i)
}
}
return primes
}
```
if isPrime(i) { // cannot find 'isPrime' in scope
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```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]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// 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
}
if n == 2 {
return true
}
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 == 1 {
return false
}
if n == 2 {
return true
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
if i.isPrime() {
primes.append(i)
}
}
return primes
}
extension Int {
func isPrime() -> Bool {
guard self > 1 else {
return false
}
for i in 2..<self {
if self % 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]()
for i in 2..<n {
if i.isPrime() {
primes.append(i)
}
}
return primes
}
extension Int {
func isPrime() -> Bool {
guard self > 1 else {
return false
}
for i in 2..<self {
if self % i == 0 {
return false
}
}
return true
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [2]
for i in stride(from: 3, through: n, by: 2) {
var isPrime = true
for j in 2...i/2 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```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 = [2]
for i in stride(from: 3, through: n, by: 2) {
var isPrime = true
for j in 2...i/2 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [2]
var i = 3
while i < n {
if isPrime(i) {
primes.append(i)
}
i += 1
}
return primes
}
func isPrime(_ n: Int) -> Bool {
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
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 = [2]
var i = 3
while i < n {
if isPrime(i) {
primes.append(i)
}
i += 1
}
return primes
}
func isPrime(_ n: Int) -> Bool {
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```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]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
if isPrime(i) {
primes.append(i)
}
}
return primes
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
guard n > 3 else { return true }
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 primes = [Int]()
for i in 2..<n {
if isPrime(i) {
primes.append(i)
}
}
return primes
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
guard n > 3 else { return true }
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 primes = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```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]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = String(a)
let b = String(b)
let a = a.suffix(1)
let b = b.suffix(1)
let a = a.prefix(1)
let b = b.prefix(1)
let a = String(a)
let b = String(b)
let a = Int(a)!
let b = Int(b)!
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 {
let a = String(a)
let b = String(b)
let a = a.suffix(1)
let b = b.suffix(1)
let a = a.prefix(1)
let b = b.prefix(1)
let a = String(a)
let b = String(b)
let a = Int(a)!
let b = Int(b)!
return a * b
}
```
let a = a.suffix(1) // invalid redeclaration of 'a'
let b = b.suffix(1) // invalid redeclaration of 'b'
return a * b // cannot convert return expression of type 'Duration' to return type 'Int'
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var result = 1
while a != 0 || b != 0 {
result *= (a % 10) * (b % 10)
a /= 10
b /= 10
}
return result
}
```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 {
var a = a
var b = b
var result = 1
while a != 0 || b != 0 {
result *= (a % 10) * (b % 10)
a /= 10
b /= 10
}
return result
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let aUnit = a % 10
let bUnit = b % 10
return aUnit * bUnit
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let aUnit = a % 10
let bUnit = b % 10
return aUnit * bUnit
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a1 = a % 10
let b1 = b % 10
return a1 * b1
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a1 = a % 10
let b1 = b % 10
return a1 * b1
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var result = 0
while a > 0 || b > 0 {
let aUnit = a % 10
let bUnit = b % 10
result += aUnit * bUnit
a = a / 10
b = b / 10
}
return result
}
```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 {
var a = a
var b = b
var result = 0
while a > 0 || b > 0 {
let aUnit = a % 10
let bUnit = b % 10
result += aUnit * bUnit
a = a / 10
b = b / 10
}
return result
}
```
// 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 (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 (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 (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 (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 countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase, char.isVowel {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0, char.isUppercase, char.isVowel {
count += 1
}
}
return count
}
```
if index % 2 == 0, char.isUppercase, char.isVowel { // value of type 'String.Element' (aka 'Character') has no member 'isVowel'
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
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
for (index, letter) in s.enumerated() {
if vowels.contains(letter) && index % 2 == 0 {
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
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
for (index, letter) in s.enumerated() {
if vowels.contains(letter) && index % 2 == 0 {
count += 1
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
for (index, letter) in s.enumerated() {
if index % 2 == 0 {
if vowels.contains(letter) {
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
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
for (index, letter) in s.enumerated() {
if index % 2 == 0 {
if vowels.contains(letter) {
count += 1
}
}
}
return count
}
```
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 {
let vowels: [Character] = ["A", "E", "I", "O", "U"]
var count: Int = 0
for (index, char) in s.enumerated() {
if vowels.contains(char) && index % 2 == 0 {
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 {
let vowels: [Character] = ["A", "E", "I", "O", "U"]
var count: Int = 0
for (index, char) in s.enumerated() {
if vowels.contains(char) && index % 2 == 0 {
count += 1
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
let vowels: [Character] = ["A", "E", "I", "O", "U"]
for (index, character) in s.enumerated() {
if character.isUppercase, index % 2 == 0, vowels.contains(character) {
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
let vowels: [Character] = ["A", "E", "I", "O", "U"]
for (index, character) in s.enumerated() {
if character.isUppercase, index % 2 == 0, vowels.contains(character) {
count += 1
}
}
return count
}
```
func countUpper(s: String) -> Int {
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
return s.enumerated().filter { $0.offset % 2 == 0 }.filter { vowels.contains($0.element) }.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 {
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
return s.enumerated().filter { $0.offset % 2 == 0 }.filter { vowels.contains($0.element) }.count
}
```
func countUpper(s: String) -> Int {
var count = 0
let vowels: Set = ["A", "E", "I", "O", "U"]
for (index, char) in s.enumerated() {
if vowels.contains(char.uppercased()) && index % 2 == 0 {
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
let vowels: Set = ["A", "E", "I", "O", "U"]
for (index, char) in s.enumerated() {
if vowels.contains(char.uppercased()) && index % 2 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
let vowels = ["A", "E", "I", "O", "U"]
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 && vowels.contains(String(char)) {
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 {
let vowels = ["A", "E", "I", "O", "U"]
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 && vowels.contains(String(char)) {
count += 1
}
}
return count
}
```
func closestInteger(value: String) -> Int {
let value = Double(value)!
if value.truncatingRemainder(dividingBy: 1) > 0.5 {
return Int(value) + 1
} else if value.truncatingRemainder(dividingBy: 1) < 0.5 {
return Int(value)
} else {
return Int(value) - 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 value = Double(value)!
if value.truncatingRemainder(dividingBy: 1) > 0.5 {
return Int(value) + 1
} else if value.truncatingRemainder(dividingBy: 1) < 0.5 {
return Int(value)
} else {
return Int(value) - 1
}
}
```
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)
let rounded = round(number!)
let floor = floor(number!)
let ceiling = ceil(number!)
let floorDiff = abs(number! - floor)
let ceilingDiff = abs(number! - ceiling)
if floorDiff > ceilingDiff {
return Int(ceiling)
} else {
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)
let rounded = round(number!)
let floor = floor(number!)
let ceiling = ceil(number!)
let floorDiff = abs(number! - floor)
let ceilingDiff = abs(number! - ceiling)
if floorDiff > ceilingDiff {
return Int(ceiling)
} else {
return Int(rounded)
}
}
```
func closestInteger(value: String) -> Int {
let value = Double(value)!
let roundedValue = round(value)
let floorValue = floor(value)
let ceilValue = ceil(value)
if abs(value - roundedValue) > abs(value - floorValue) {
return Int(floorValue)
} else if abs(value - roundedValue) > abs(value - ceilValue) {
return Int(ceilValue)
} else {
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 value = Double(value)!
let roundedValue = round(value)
let floorValue = floor(value)
let ceilValue = ceil(value)
if abs(value - roundedValue) > abs(value - floorValue) {
return Int(floorValue)
} else if abs(value - roundedValue) > abs(value - ceilValue) {
return Int(ceilValue)
} else {
return Int(roundedValue)
}
}
```
func closestInteger(value: String) -> Int {
let number = Double(value) ?? 0
let rounded = round(number)
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 = round(number)
return Int(rounded)
}
```
func closestInteger(value: String) -> Int {
let number = Double(value)
return Int(round(number!))
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)
return Int(round(number!))
}
```
func closestInteger(value: String) -> Int {
let number = Double(value) ?? 0
let rounded = round(number)
let floor = floor(number)
let ceil = ceil(number)
if abs(rounded - number) > abs(floor - number) {
return Int(floor)
} else if abs(rounded - number) > abs(ceil - number) {
return Int(ceil)
} else {
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 = round(number)
let floor = floor(number)
let ceil = ceil(number)
if abs(rounded - number) > abs(floor - number) {
return Int(floor)
} else if abs(rounded - number) > abs(ceil - number) {
return Int(ceil)
} else {
return Int(rounded)
}
}
```
func closestInteger(value: String) -> Int {
let number = Double(value)
if number!.truncatingRemainder(dividingBy: 1) < 0.5 {
return Int(number!)
} else {
return Int(number!) + 1
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)
if number!.truncatingRemainder(dividingBy: 1) < 0.5 {
return Int(number!)
} else {
return Int(number!) + 1
}
}
```
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let value = Double(value) ?? 0
let roundedValue = round(value)
let floorValue = floor(value)
let ceilValue = ceil(value)
if abs(value - roundedValue) > 0.5 {
return Int(roundedValue)
} else if abs(value - floorValue) == abs(value - ceilValue) {
return Int(roundedValue)
} else if abs(value - floorValue) < abs(value - ceilValue) {
return Int(floorValue)
} else {
return Int(ceilValue)
}
}
```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 value = Double(value) ?? 0
let roundedValue = round(value)
let floorValue = floor(value)
let ceilValue = ceil(value)
if abs(value - roundedValue) > 0.5 {
return Int(roundedValue)
} else if abs(value - floorValue) == abs(value - ceilValue) {
return Int(roundedValue)
} else if abs(value - floorValue) < abs(value - ceilValue) {
return Int(floorValue)
} else {
return Int(ceilValue)
}
}
```
func closestInteger(value: String) -> Int {
let number = Double(value)
if number == nil {
return 0
}
if number! >= 0 {
return Int(floor(number!))
} else {
return Int(ceil(number!))
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)
if number == nil {
return 0
}
if number! >= 0 {
return Int(floor(number!))
} else {
return Int(ceil(number!))
}
}
```
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value) ?? 0
let rounded = round(number)
let floor = floor(number)
let ceil = ceil(number)
let distanceToFloor = abs(number - floor)
let distanceToCeil = abs(number - ceil)
if distanceToFloor == distanceToCeil {
return Int(rounded)
} else if distanceToFloor < distanceToCeil {
return Int(floor)
} else {
return Int(ceil)
}
}
```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 = round(number)
let floor = floor(number)
let ceil = ceil(number)
let distanceToFloor = abs(number - floor)
let distanceToCeil = abs(number - ceil)
if distanceToFloor == distanceToCeil {
return Int(rounded)
} else if distanceToFloor < distanceToCeil {
return Int(floor)
} else {
return Int(ceil)
}
}
```
func makeAPile(n: Int) -> [Int] {
var pile = [n]
var stones = n
for _ in 1..<n {
if stones % 2 == 0 {
stones += 1
} else {
stones += 2
}
pile.append(stones)
}
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]
var stones = n
for _ in 1..<n {
if stones % 2 == 0 {
stones += 1
} else {
stones += 2
}
pile.append(stones)
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [n]
var currentLevel = n
while currentLevel > 1 {
if currentLevel % 2 == 0 {
pile.insert(currentLevel + 1, at: 0)
} else {
pile.insert(currentLevel + 2, at: 0)
}
currentLevel -= 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]
var currentLevel = n
while currentLevel > 1 {
if currentLevel % 2 == 0 {
pile.insert(currentLevel + 1, at: 0)
} else {
pile.insert(currentLevel + 2, at: 0)
}
currentLevel -= 1
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [n]
var stones = n
var odd = true
for _ in 1..<n {
odd ? (stones += 2) : (stones += 1)
pile.append(stones)
odd = !odd
}
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]
var stones = n
var odd = true
for _ in 1..<n {
odd ? (stones += 2) : (stones += 1)
pile.append(stones)
odd = !odd
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var stones = n
for _ in 0..<n {
pile.append(stones)
if stones % 2 == 0 {
stones += 1
} else {
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)
if stones % 2 == 0 {
stones += 1
} else {
stones += 2
}
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
func makeAPile(n: Int) -> [Int] {
return Array(repeating: n, count: n)
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 1) == [1]
func makeAPile(n: Int) -> [Int] {
return Array(repeating: n, count: n)
}
// makeAPile(n: 4) == [4, 6, 8, 10]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 2) == [2, 4]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 5) == [5, 7, 9, 11, 13]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 6) == [6, 8, 10, 12, 14, 16]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 7) == [7, 9, 11, 13, 15, 17, 19]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 8) == [8, 10, 12, 14, 16, 18, 20, 22]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 9) == [9, 11, 13, 15, 17, 19, 21, 23, 25]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 0..<n {
result.append(current)
if current % 2 == 0 {
current += 1
} else {
current += 2
}
}
return result
}
// makeAPile(n: 10) == [10, 12, 14, 16, 18, 20, 22, 24, 2
func makeAPile(n: Int) -> [Int] { // invalid redeclaration of 'makeAPile(n:)'
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 1...n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result: [Int] = []
var current = n
for _ in 1...n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 1 {
pile.append(i + 1)
} else {
pile.append(i + 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]()
for i in 1...n {
if i % 2 == 1 {
pile.append(i + 1)
} else {
pile.append(i + 2)
}
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var currentLevelStones = n
for _ in 0..<n {
result.append(currentLevelStones)
currentLevelStones += currentLevelStones % 2 == 0 ? 2 : 1
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var currentLevelStones = n
for _ in 0..<n {
result.append(currentLevelStones)
currentLevelStones += currentLevelStones % 2 == 0 ? 2 : 1
}
return result
}
// makeAPile(n: 4) == [4, 6, 8, 10]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var currentLevelStones = n
for _ in 0..<n {
result.append(currentLevelStones)
currentLevelStones += currentLevelStones % 2 == 0 ? 2 : 1
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [n]
var current = n
while current > 1 {
current = current % 2 == 0 ? current - 1 : current + 1
pile.append(current)
}
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]
var current = n
while current > 1 {
current = current % 2 == 0 ? current - 1 : current + 1
pile.append(current)
}
return pile
}
```
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var currentLevelStones = n
result.append(n)
while currentLevelStones > 1 {
if currentLevelStones % 2 == 0 {
currentLevelStones += 1
} else {
currentLevelStones += 2
}
result.append(currentLevelStones)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var currentLevelStones = n
result.append(n)
while currentLevelStones > 1 {
if currentLevelStones % 2 == 0 {
currentLevelStones += 1
} else {
currentLevelStones += 2
}
result.append(currentLevelStones)
}
return result
}
```
func wordsString(s: String) -> [String] {
return s.components(separatedBy: CharacterSet(charactersIn: " ,"))
}
```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: CharacterSet(charactersIn: " ,"))
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: CharacterSet(charactersIn: ", "))
}
```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: CharacterSet(charactersIn: ", "))
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: CharacterSet.whitespacesAndNewlines)
}
```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: CharacterSet.whitespacesAndNewlines)
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: CharacterSet(charactersIn: " ,"))
}
```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: CharacterSet(charactersIn: " ,"))
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: CharacterSet(charactersIn: ", "))
}
```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: CharacterSet(charactersIn: ", "))
}
```
// 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: CharacterSet(charactersIn: ", "))
}
```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: CharacterSet(charactersIn: ", "))
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result: Int = 0
if x > y {
let temp: Int = x
x = y
y = temp
}
for i in x...y {
if i % 2 == 0 {
result = i
}
}
if result == 0 {
result = -1
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result: Int = 0
if x > y {
let temp: Int = x
x = y
y = temp
}
for i in x...y {
if i % 2 == 0 {
result = i
}
}
if result == 0 {
result = -1
}
return result
}
```
x = y // cannot assign to value: 'x' is a 'let' constant
y = temp // cannot assign to value: 'y' is a 'let' constant
func chooseNum(x: Int, y: Int) -> Int {
// Write your code here
var evenNum = -1
if x % 2 == 0 && y % 2 == 0 {
if x <= y {
evenNum = y
} else {
evenNum = x
}
}
return evenNum
}
```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 {
// Write your code here
var evenNum = -1
if x % 2 == 0 && y % 2 == 0 {
if x <= y {
evenNum = y
} else {
evenNum = x
}
}
return evenNum
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var evenNums = [Int]()
for num in x...y {
if num % 2 == 0 {
evenNums.append(num)
}
}
if evenNums.isEmpty {
return -1
} else {
return evenNums.last!
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var evenNums = [Int]()
for num in x...y {
if num % 2 == 0 {
evenNums.append(num)
}
}
if evenNums.isEmpty {
return -1
} else {
return evenNums.last!
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
// Write your code here
var maxEven = -1
if x % 2 == 0 && x <= y {
maxEven = x
}
for i in x...y {
if i % 2 == 0 && i > maxEven {
maxEven = i
}
}
return maxEven
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
// Write your code here
var maxEven = -1
if x % 2 == 0 && x <= y {
maxEven = x
}
for i in x...y {
if i % 2 == 0 && i > maxEven {
maxEven = i
}
}
return maxEven
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 && y % 2 == 0 && x <= y {
return y
} else if x % 2 == 1 && y % 2 == 1 && x >= y {
return -1
} else if x % 2 == 1 && y % 2 == 0 && x >= y {
return y
} else if x % 2 == 0 && y % 2 == 1 && x <= y {
return x
} else if x % 2 == 0 && y % 2 == 1 && x >= y {
return x
} else if x % 2 == 1 && y % 2 == 0 && x <= y {
return y
} else {
return -1
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 && y % 2 == 0 && x <= y {
return y
} else if x % 2 == 1 && y % 2 == 1 && x >= y {
return -1
} else if x % 2 == 1 && y % 2 == 0 && x >= y {
return y
} else if x % 2 == 0 && y % 2 == 1 && x <= y {
return x
} else if x % 2 == 0 && y % 2 == 1 && x >= y {
return x
} else if x % 2 == 1 && y % 2 == 0 && x <= y {
return y
} else {
return -1
}
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x <= 0 || y <= 0 {
return -1
}
var result: Int = -1
for i in x ... y {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x <= 0 || y <= 0 {
return -1
}
var result: Int = -1
for i in x ... y {
if i % 2 == 0 {
result = i
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
// your code here
var evenNum = -1
for i in x...y {
if i % 2 == 0 {
evenNum = i
}
}
return evenNum
}
```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
var evenNum = -1
for i in x...y {
if i % 2 == 0 {
evenNum = i
}
}
return evenNum
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
if x >= y {
return -1
} else {
if x % 2 == 1 {
if y % 2 == 1 {
return y - 1
} else {
return y
}
} else {
return y
}
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x >= y {
return -1
} else {
if x % 2 == 1 {
if y % 2 == 1 {
return y - 1
} else {
return y
}
} else {
return y
}
}
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var evenNumbers = [Int]()
for number in x...y {
if number % 2 == 0 {
evenNumbers.append(number)
}
}
return evenNumbers.last ?? -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var evenNumbers = [Int]()
for number in x...y {
if number % 2 == 0 {
evenNumbers.append(number)
}
}
return evenNumbers.last ?? -1
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
if x >= y {
return -1
} else {
for i in x..<y {
if i % 2 == 0 {
return i
}
}
}
return -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x >= y {
return -1
} else {
for i in x..<y {
if i % 2 == 0 {
return i
}
}
}
return -1
}
```
// XCTAssertTrue failed
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 = Double(sum) / Double(m - n + 1)
let roundedAvg = Int(round(avg))
return .success(String(roundedAvg, 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 = Double(sum) / Double(m - n + 1)
let roundedAvg = Int(round(avg))
return .success(String(roundedAvg, 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(Int.max) }
let avg = (Double(n) + Double(m)) / 2
let roundedAvg = Int(round(avg))
return .success(String(roundedAvg, 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(Int.max) }
let avg = (Double(n) + Double(m)) / 2
let roundedAvg = Int(round(avg))
return .success(String(roundedAvg, 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 avg = Double(n + m) / 2
let roundedAvg = Int(round(avg))
return .success(String(roundedAvg, 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 avg = Double(n + m) / 2
let roundedAvg = Int(round(avg))
return .success(String(roundedAvg, 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(Int(0)) }
let average = (n + m) / 2
return .success(String(average, 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(Int(0)) }
let average = (n + m) / 2
return .success(String(average, 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(n) }
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(n) }
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 average = sum / (m - n + 1)
return .success(String(average, 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 average = sum / (m - n + 1)
return .success(String(average, 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(Int.max) }
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(Int.max) }
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(Int(-1)) }
let average = Double((n + m) / 2)
let roundedAverage = Int(round(average))
return .success(String(roundedAverage, 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(Int(-1)) }
let average = Double((n + m) / 2)
let roundedAverage = Int(round(average))
return .success(String(roundedAverage, 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] {
// Write 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] {
// Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func uniqueDigits(x: [Int]) -> [Int] {
var arr = x
for i in 0 ..< arr.count {
var temp = arr[i]
var isEven = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
isEven = true
break
}
temp = temp / 10
}
if isEven {
arr.remove(at: i)
i -= 1
}
}
return arr.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] {
var arr = x
for i in 0 ..< arr.count {
var temp = arr[i]
var isEven = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
isEven = true
break
}
temp = temp / 10
}
if isEven {
arr.remove(at: i)
i -= 1
}
}
return arr.sorted()
}
```
i -= 1 // left side of mutating operator isn't mutable: 'i' is a 'let' constant
func uniqueDigits(x: [Int]) -> [Int] {
let evenDigits = [0, 2, 4, 6, 8]
let evenDigitsSet = Set(evenDigits)
let filtered = x.filter {
let digits = $0.digits
return !digits.contains(where: { evenDigitsSet.contains($0) })
}
return filtered.sorted()
}
extension Int {
var digits: [Int] {
var digits: [Int] = []
var n = self
while n != 0 {
let digit = n % 10
digits.append(digit)
n /= 10
}
return digits.reversed()
}
}
```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] {
let evenDigits = [0, 2, 4, 6, 8]
let evenDigitsSet = Set(evenDigits)
let filtered = x.filter {
let digits = $0.digits
return !digits.contains(where: { evenDigitsSet.contains($0) })
}
return filtered.sorted()
}
// MARK: - Extensions
extension Int {
var digits: [Int] {
var digits: [Int] = []
var n = self
while n != 0 {
let digit = n % 10
digits.append(digit)
n /= 10
}
return digits.reversed()
}
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !i.description.contains("2") && !i.description.contains("4") && !i.description.contains("6") && !i.description.contains("8") {
result.append(i)
}
}
return result.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] {
var result = [Int]()
for i in x {
if !i.description.contains("2") && !i.description.contains("4") && !i.description.contains("6") && !i.description.contains("8") {
result.append(i)
}
}
return result.sorted()
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
let evenDigits = [2, 4, 6, 8]
var result = [Int]()
for num in x {
var isEven = false
var temp = num
while temp > 0 {
let digit = temp % 10
if evenDigits.contains(digit) {
isEven = true
break
}
temp /= 10
}
if !isEven {
result.append(num)
}
}
result.sort()
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] {
let evenDigits = [2, 4, 6, 8]
var result = [Int]()
for num in x {
var isEven = false
var temp = num
while temp > 0 {
let digit = temp % 10
if evenDigits.contains(digit) {
isEven = true
break
}
temp /= 10
}
if !isEven {
result.append(num)
}
}
result.sort()
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
// TODO: Write your code here
return []
}
```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] {
// TODO: Write your code here
return []
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
// TODO: Write 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] {
// TODO: Write your code here
}
```
} // missing return in global function expected to return '[Int]'
func uniqueDigits(x: [Int]) -> [Int] {
let evenDigits = [0, 2, 4, 6, 8]
return x.filter { !evenDigits.contains(where: { $0 == $0 % 10 })}
}
```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] {
let evenDigits = [0, 2, 4, 6, 8]
return x.filter { !evenDigits.contains(where: { $0 == $0 % 10 })}
}
```
return x.filter { !evenDigits.contains(where: { $0 == $0 % 10 })} // contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.description.range(of: "[0-9]*?[^02468]$", options: .regularExpression) != nil }
}
```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.range(of: "[0-9]*?[^02468]$", options: .regularExpression) != nil }
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
// TODO: Write your code here
return []
}
```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] {
// TODO: Write your code here
return []
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let arr = arr.filter { $0 >= 1 && $0 <= 9 }
let arr = arr.sorted { $0 > $1 }
var arr = arr.map { String($0) }
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") }
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") }
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") }
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") }
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") }
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") }
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") }
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") }
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") }
return arr
}
```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 arr = arr.filter { $0 >= 1 && $0 <= 9 }
let arr = arr.sorted { $0 > $1 }
var arr = arr.map { String($0) }
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") }
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") }
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") }
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") }
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") }
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") }
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") }
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") }
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") }
return arr
}
```
let arr = arr.sorted { $0 > $1 } // invalid redeclaration of 'arr'
func byLength(arr: [Int]) -> [String] {
let arr = arr.filter { $0 > 0 && $0 <= 9 }
let arr = arr.sorted { $0 < $1 }
let arr = arr.reversed()
var arr = arr.map { String($0) }
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") }
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") }
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") }
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") }
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") }
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") }
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") }
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") }
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") }
return arr
}
```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 arr = arr.filter { $0 > 0 && $0 <= 9 }
let arr = arr.sorted { $0 < $1 }
let arr = arr.reversed()
var arr = arr.map { String($0) }
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") }
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") }
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") }
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") }
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") }
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") }
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") }
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") }
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") }
return arr
}
```
let arr = arr.sorted { $0 < $1 } // invalid redeclaration of 'arr'
func byLength(arr: [Int]) -> [String] {
// Write your code here
var result = arr.filter { $0 >= 1 && $0 <= 9 }
result.sort()
result = result.reversed()
var resultString = [String]()
for i in result {
switch i {
case 1:
resultString.append("One")
case 2:
resultString.append("Two")
case 3:
resultString.append("Three")
case 4:
resultString.append("Four")
case 5:
resultString.append("Five")
case 6:
resultString.append("Six")
case 7:
resultString.append("Seven")
case 8:
resultString.append("Eight")
case 9:
resultString.append("Nine")
default:
break
}
}
return resultString
}
```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] {
// Write your code here
var result = arr.filter { $0 >= 1 && $0 <= 9 }
result.sort()
result = result.reversed()
var resultString = [String]()
for i in result {
switch i {
case 1:
resultString.append("One")
case 2:
resultString.append("Two")
case 3:
resultString.append("Three")
case 4:
resultString.append("Four")
case 5:
resultString.append("Five")
case 6:
resultString.append("Six")
case 7:
resultString.append("Seven")
case 8:
resultString.append("Eight")
case 9:
resultString.append("Nine")
default:
break
}
}
return resultString
}
```
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter{ $0 > 0 && $0 < 10 }
arr.sort(by: >)
var result = [String]()
for i in arr {
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
}
```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 arr = arr
arr = arr.filter{ $0 > 0 && $0 < 10 }
arr.sort(by: >)
var result = [String]()
for i in arr {
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
}
```
func byLength(arr: [Int]) -> [String] {
// Write your code here
var result = arr.filter { $0 > 0 && $0 < 10 }
result.sort(by: <)
result.reverse()
return result.map { String($0) }
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
// Write your code here
var result = arr.filter { $0 > 0 && $0 < 10 }
result.sort(by: <)
result.reverse()
return result.map { String($0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
// Write your code here
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
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 = result.sorted(by: {$0.count < $1.count})
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] {
// Write your code here
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
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 = result.sorted(by: {$0.count < $1.count})
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr where i >= 1 && i <= 9 {
result.append(i.description)
}
result.sort()
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 where i >= 1 && i <= 9 {
result.append(i.description)
}
result.sort()
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 > 0 && $0 < 10 }.sorted().map { String($0) }.map { $0.map { String(Int($0.asciiValue! - 48)) }.joined(separator: "") }
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 > 0 && $0 < 10 }.sorted().map { String($0) }.map { $0.map { String(Int($0.asciiValue! - 48)) }.joined(separator: "") }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
// your code here
var arr = arr
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
result.sort {
$0.count < $1.count
}
var result2 = [String]()
for i in result {
switch i {
case "1":
result2.append("One")
case "2":
result2.append("Two")
case "3":
result2.append("Three")
case "4":
result2.append("Four")
case "5":
result2.append("Five")
case "6":
result2.append("Six")
case "7":
result2.append("Seven")
case "8":
result2.append("Eight")
case "9":
result2.append("Nine")
default:
break
}
}
return result2
}
```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] {
// your code here
var arr = arr
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
result.sort {
$0.count < $1.count
}
var result2 = [String]()
for i in result {
switch i {
case "1":
result2.append("One")
case "2":
result2.append("Two")
case "3":
result2.append("Three")
case "4":
result2.append("Four")
case "5":
result2.append("Five")
case "6":
result2.append("Six")
case "7":
result2.append("Seven")
case "8":
result2.append("Eight")
case "9":
result2.append("Nine")
default:
break
}
}
return result2
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 > 0 && $0 <= 9 }.map { String($0) }.sorted(by: >).map {
switch $0 {
case "1":
return "One"
case "2":
return "Two"
case "3":
return "Three"
case "4":
return "Four"
case "5":
return "Five"
case "6":
return "Six"
case "7":
return "Seven"
case "8":
return "Eight"
case "9":
return "Nine"
default:
return ""
}
}
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 > 0 && $0 <= 9 }.map { String($0) }.sorted(by: >).map {
switch $0 {
case "1":
return "One"
case "2":
return "Two"
case "3":
return "Three"
case "4":
return "Four"
case "5":
return "Five"
case "6":
return "Six"
case "7":
return "Seven"
case "8":
return "Eight"
case "9":
return "Nine"
default:
return ""
}
}
}
```
func f(n: Int) -> [Int] {
var array = [Int]()
for i in 1...n {
if i % 2 == 0 {
array.append(i)
} else {
var sum = 0
for j in 1...i {
sum += j
}
array.append(sum)
}
}
return array
}
```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 array = [Int]()
for i in 1...n {
if i % 2 == 0 {
array.append(i)
} else {
var sum = 0
for j in 1...i {
sum += j
}
array.append(sum)
}
}
return array
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
var a = [Int]()
for i in 1...n {
if i % 2 == 1 {
var sum = 0
for j in 1...i {
sum += j
}
a.append(sum)
} else {
var fact = 1
for j in 1...i {
fact *= j
}
a.append(fact)
}
}
return a
}
```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 a = [Int]()
for i in 1...n {
if i % 2 == 1 {
var sum = 0
for j in 1...i {
sum += j
}
a.append(sum)
} else {
var fact = 1
for j in 1...i {
fact *= j
}
a.append(fact)
}
}
return a
}
```
func f(n: Int) -> [Int] {
var a = [Int]()
for i in 1...n {
if i % 2 == 1 {
var sum = 0
for j in 1...i {
sum += j
}
a.append(sum)
} else {
var factorial = 1
for j in 1...i {
factorial *= j
}
a.append(factorial)
}
}
return a
}
```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 a = [Int]()
for i in 1...n {
if i % 2 == 1 {
var sum = 0
for j in 1...i {
sum += j
}
a.append(sum)
} else {
var factorial = 1
for j in 1...i {
factorial *= j
}
a.append(factorial)
}
}
return a
}
```
func f(n: Int) -> [Int] {
var numbers = [Int]()
for i in 1...n {
if i % 2 == 0 {
var fact = 1
for j in 1...i {
fact *= j
}
numbers.append(fact)
} else {
var sum = 0
for j in 1...i {
sum += j
}
numbers.append(sum)
}
}
return numbers
}
```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 numbers = [Int]()
for i in 1...n {
if i % 2 == 0 {
var fact = 1
for j in 1...i {
fact *= j
}
numbers.append(fact)
} else {
var sum = 0
for j in 1...i {
sum += j
}
numbers.append(sum)
}
}
return numbers
}
```
func f(n: Int) -> [Int] {
var numbers = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial: Int = 1
for j in 1...i {
factorial *= j
}
numbers.append(factorial)
} else {
var sum: Int = 0
for j in 1...i {
sum += j
}
numbers.append(sum)
}
}
return numbers
}
```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 numbers = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial: Int = 1
for j in 1...i {
factorial *= j
}
numbers.append(factorial)
} else {
var sum: Int = 0
for j in 1...i {
sum += j
}
numbers.append(sum)
}
}
return numbers
}
```
func f(n: Int) -> [Int] {
var array = [Int]()
for i in 1...n {
if i % 2 == 0 {
array.append(factorial(i))
} else {
array.append(sum(i))
}
}
return array
}
func factorial(_ number: Int) -> Int {
if number == 1 {
return 1
} else {
return number * factorial(number - 1)
}
}
func sum(_ number: Int) -> Int {
var sum = 0
for i in 1...number {
sum += i
}
return sum
}
```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 array = [Int]()
for i in 1...n {
if i % 2 == 0 {
array.append(factorial(i))
} else {
array.append(sum(i))
}
}
return array
}
func factorial(_ number: Int) -> Int {
if number == 1 {
return 1
} else {
return number * factorial(number - 1)
}
}
func sum(_ number: Int) -> Int {
var sum = 0
for i in 1...number {
sum += i
}
return sum
}
```
func f(n: Int) -> [Int] {
var a = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial = 1
for j in 1...i {
factorial *= j
}
a.append(factorial)
} else {
var sum = 0
for j in 1...i {
sum += j
}
a.append(sum)
}
}
return a
}
```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 a = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial = 1
for j in 1...i {
factorial *= j
}
a.append(factorial)
} else {
var sum = 0
for j in 1...i {
sum += j
}
a.append(sum)
}
}
return a
}
```
func f(n: Int) -> [Int] {
var res = [Int]()
for i in 1...n {
if i % 2 == 0 {
var fact = 1
for j in 1...i {
fact *= j
}
res.append(fact)
} else {
var sum = 0
for j in 1...i {
sum += j
}
res.append(sum)
}
}
return res
}
```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 res = [Int]()
for i in 1...n {
if i % 2 == 0 {
var fact = 1
for j in 1...i {
fact *= j
}
res.append(fact)
} else {
var sum = 0
for j in 1...i {
sum += j
}
res.append(sum)
}
}
return res
}
```
func f(n: Int) -> [Int] {
var arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
var fact = 1
for j in 1...i {
fact *= j
}
arr.append(fact)
} else {
var sum = 0
for k in 1...i {
sum += k
}
arr.append(sum)
}
}
return arr
}
```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 arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
var fact = 1
for j in 1...i {
fact *= j
}
arr.append(fact)
} else {
var sum = 0
for k in 1...i {
sum += k
}
arr.append(sum)
}
}
return arr
}
```
func f(n: Int) -> [Int] {
var numbers = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial = 1
for j in 1...i {
factorial *= j
}
numbers.append(factorial)
} else {
var sum = 0
for j in 1...i {
sum += j
}
numbers.append(sum)
}
}
return numbers
}
```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 numbers = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial = 1
for j in 1...i {
factorial *= j
}
numbers.append(factorial)
} else {
var sum = 0
for j in 1...i {
sum += j
}
numbers.append(sum)
}
}
return numbers
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if isPalindrome(n: i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
func isPalindrome(n: Int) -> Bool {
let str = String(n)
var i = 0
var j = str.count - 1
while i < j {
if str[i] != str[j] {
return false
}
i += 1
j -= 1
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if isPalindrome(n: i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
func isPalindrome(n: Int) -> Bool {
let str = String(n)
var i = 0
var j = str.count - 1
while i < j {
if str[i] != str[j] {
return false
}
i += 1
j -= 1
}
return true
}
```
if str[i] != str[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if str[i] != str[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
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)
}
```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)
}
```
if isPalindrome(i) { // cannot find 'isPalindrome' in scope
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if i == reverse(i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
func reverse(_ n: Int) -> Int {
var n = n
var reversed = 0
while n > 0 {
reversed = reversed * 10 + n % 10
n /= 10
}
return 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 evenCount = 0
var oddCount = 0
for i in 1...n {
if i == reverse(i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
func reverse(_ n: Int) -> Int {
var n = n
var reversed = 0
while n > 0 {
reversed = reversed * 10 + n % 10
n /= 10
}
return reversed
}
```
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 {
let str = String(num)
var left = 0
var right = str.count - 1
while left < right {
if str[str.index(str.startIndex, offsetBy: left)] != str[str.index(str.startIndex, offsetBy: right)] {
return false
}
left += 1
right -= 1
}
return true
}
```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 {
let str = String(num)
var left = 0
var right = str.count - 1
while left < right {
if str[str.index(str.startIndex, offsetBy: left)] != str[str.index(str.startIndex, offsetBy: right)] {
return false
}
left += 1
right -= 1
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
func countPalindromes(n: Int) -> Int {
var count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
// Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11.
// 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 countPalindromes(n: Int) -> Int {
var count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return count
}
// Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11.
// 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 countPalindromes(n: Int) -> Int {
var count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return count
}
// Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11.
// 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 countPalindromes(n: Int) -> Int {
var count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return count
}
// Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11.
// 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 countPalindromes(n: Int) -> Int {
var count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return count
}
// Given a positive integer n, return the number of palind
if isPalindrome(i) { // cannot find 'isPalindrome' in scope
if isPalindrome(i) { // cannot find 'isPalindrome' in scope
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 {
let str = "\(n)"
let reversed = String(str.reversed())
return str == 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 {
let str = "\(n)"
let reversed = String(str.reversed())
return str == reversed
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
// 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(_ x: Int) -> Bool {
let str = String(x)
for i in 0..<str.count / 2 {
if str[str.index(str.startIndex, offsetBy: i)] != str[str.index(str.endIndex, offsetBy: -i - 1)] {
return false
}
}
return true
}
```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)
}
// Given an integer, return true if the number is a palindrome.
// Example 1:
// Explanation:
// 121 is a palindrome.
// Example 2:
// Explanation:
// 123 is not a palindrome.
func isPalindrome(_ x: Int) -> Bool {
let str = String(x)
for i in 0..<str.count / 2 {
if str[str.index(str.startIndex, offsetBy: i)] != str[str.index(str.endIndex, offsetBy: -i - 1)] {
return false
}
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if isPalindrome(num: i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
func isPalindrome(num: Int) -> Bool {
let str = String(num)
var leftIndex = 0
var rightIndex = str.count - 1
while leftIndex < rightIndex {
if str[str.index(str.startIndex, offsetBy: leftIndex)] != str[str.index(str.startIndex, offsetBy: rightIndex)] {
return false
}
leftIndex += 1
rightIndex -= 1
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
if isPalindrome(num: i) {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
// Given an integer, return true if it's a palindrome
func isPalindrome(num: Int) -> Bool {
let str = String(num)
var leftIndex = 0
var rightIndex = str.count - 1
while leftIndex < rightIndex {
if str[str.index(str.startIndex, offsetBy: leftIndex)] != str[str.index(str.startIndex, offsetBy: rightIndex)] {
return false
}
leftIndex += 1
rightIndex -= 1
}
return true
}
```
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 {
let str = String(n)
let reversed = String(str.reversed())
return str == 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 {
let str = String(n)
let reversed = String(str.reversed())
return str == reversed
}
```
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
count += 1
} else {
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
} else {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
let digits = String(num).map { Int(String($0))! }
let sum = digits.reduce(0, +)
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 {
let digits = String(num).map { Int(String($0))! }
let sum = digits.reduce(0, +)
if sum > 0 {
count += 1
}
}
return count
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
count += 1
} else {
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
} else {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = abs(num)
while n > 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = abs(num)
while n > 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for i in arr {
if i < 0 {
var sum = 0
var n = i
while n != 0 {
sum += abs(n % 10)
n /= 10
}
if sum > 0 {
count += 1
}
} else {
if i > 0 {
var sum = 0
var n = i
while n != 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for i in arr {
if i < 0 {
var sum = 0
var n = i
while n != 0 {
sum += abs(n % 10)
n /= 10
}
if sum > 0 {
count += 1
}
} else {
if i > 0 {
var sum = 0
var n = i
while n != 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
let digits = String(num).compactMap { Int(String($0)) }
let sum = digits.reduce(0, +)
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 {
let digits = String(num).compactMap { Int(String($0)) }
let sum = digits.reduce(0, +)
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for i in arr {
var sum = 0
var num = i
while num != 0 {
sum += abs(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 i in arr {
var sum = 0
var num = i
while num != 0 {
sum += abs(num % 10)
num /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for i in arr {
if i < 0 {
let str = String(i)
let arr = Array(str)
var sum = 0
for j in arr {
if j == "-" {
continue
}
let num = Int(String(j)) ?? 0
sum += num
}
if sum > 0 {
count += 1
}
} else {
let str = String(i)
let arr = Array(str)
var sum = 0
for j in arr {
let num = Int(String(j)) ?? 0
sum += num
}
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 i in arr {
if i < 0 {
let str = String(i)
let arr = Array(str)
var sum = 0
for j in arr {
if j == "-" {
continue
}
let num = Int(String(j)) ?? 0
sum += num
}
if sum > 0 {
count += 1
}
} else {
let str = String(i)
let arr = Array(str)
var sum = 0
for j in arr {
let num = Int(String(j)) ?? 0
sum += num
}
if sum > 0 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for i in arr {
var sum = 0
var num = i
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 i in arr {
var sum = 0
var num = i
while num > 0 {
sum += num % 10
num /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for i in arr {
if i < 0 {
var temp = i
var sum = 0
while temp < 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
} else {
var temp = i
var sum = 0
while temp > 0 {
sum += temp % 10
temp /= 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 i in arr {
if i < 0 {
var temp = i
var sum = 0
while temp < 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
} else {
var temp = i
var sum = 0
while temp > 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i+1] {
let last = arr.removeLast()
arr.insert(last, at: 0)
} else {
i += 1
}
}
return arr.isSorted()
}
```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 i = 0
while i < arr.count - 1 {
if arr[i] > arr[i+1] {
let last = arr.removeLast()
arr.insert(last, at: 0)
} else {
i += 1
}
}
return arr.isSorted()
}
```
return arr.isSorted() // value of type '[Int]' has no member 'isSorted'
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
} else {
i += 1
}
}
return true
}
```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 {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
} else {
i += 1
}
}
return true
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
var arr = arr
var count = 0
while arr[0] != 1 {
arr.append(arr[0])
arr.removeFirst()
count += 1
}
if count % 2 == 0 {
return true
}
return false
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
var arr = arr
var count = 0
while arr[0] != 1 {
arr.append(arr[0])
arr.removeFirst()
count += 1
}
if count % 2 == 0 {
return true
}
return false
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else {
return true
}
var arr = arr
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
arr.append(arr.removeFirst())
i = 0
} else {
i += 1
}
}
return true
}
```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 {
guard arr.count > 1 else {
return true
}
var arr = arr
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
arr.append(arr.removeFirst())
i = 0
} else {
i += 1
}
}
return true
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i+1] {
let temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```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 i = 0
while i < arr.count - 1 {
if arr[i] > arr[i+1] {
let temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
var arr = arr
var count = 0
while arr.count > 0 {
if arr.last! > arr.first! {
arr.append(arr.removeFirst())
count += 1
} else {
arr.removeLast()
}
}
return count <= arr.count
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
var arr = arr
var count = 0
while arr.count > 0 {
if arr.last! > arr.first! {
arr.append(arr.removeFirst())
count += 1
} else {
arr.removeLast()
}
}
return count <= arr.count
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
var arr = arr
var count = 0
while count < arr.count {
if arr[count] > arr[count + 1] {
arr.insert(arr.removeLast(), at: 0)
} else {
count += 1
}
}
return true
}
```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
var arr = arr
var count = 0
while count < arr.count {
if arr[count] > arr[count + 1] {
arr.insert(arr.removeLast(), at: 0)
} else {
count += 1
}
}
return true
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
if arr.isEmpty { return true }
var arr = arr
var i = arr.count - 1
while i > 0 {
if arr[i] < arr[i - 1] {
arr.append(arr[i])
arr.remove(at: i)
i = arr.count - 1
} else {
i -= 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
if arr.isEmpty { return true }
var arr = arr
var i = arr.count - 1
while i > 0 {
if arr[i] < arr[i - 1] {
arr.append(arr[i])
arr.remove(at: i)
i = arr.count - 1
} else {
i -= 1
}
}
return arr == arr.sorted()
}
```
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
if arr.isEmpty {
return true
}
var arr = arr
var count = 0
while arr != arr.sorted() {
let last = arr.popLast()
arr.insert(last!, at: 0)
count += 1
}
if count % 2 == 0 {
return true
}
return false
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
// Write your code here
if arr.isEmpty {
return true
}
var arr = arr
var count = 0
while arr != arr.sorted() {
let last = arr.popLast()
arr.insert(last!, at: 0)
count += 1
}
if count % 2 == 0 {
return true
}
return false
}
```
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```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 {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
// Write your code here
var lst1 = lst1
var lst2 = lst2
var count = 0
for _ in lst1 {
if lst1[count] % 2 == 0 {
lst1[count] = lst2[count]
}
count += 1
}
for _ in lst1 {
if lst1[count] % 2 == 0 {
return "YES"
}
count += 1
}
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 {
// Write your code here
var lst1 = lst1
var lst2 = lst2
var count = 0
for _ in lst1 {
if lst1[count] % 2 == 0 {
lst1[count] = lst2[count]
}
count += 1
}
for _ in lst1 {
if lst1[count] % 2 == 0 {
return "YES"
}
count += 1
}
return "NO"
}
```
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func exchange(lst1: [Int], lst2: [Int]) -> String {
// your code here
var lst1 = lst1
var lst2 = lst2
var lst1Even = 0
var lst2Odd = 0
for i in lst1 {
if i % 2 == 0 {
lst1Even += 1
}
}
for i in lst2 {
if i % 2 != 0 {
lst2Odd += 1
}
}
if lst1Even == lst1.count && lst2Odd == lst2.count {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
// your code here
var lst1 = lst1
var lst2 = lst2
var lst1Even = 0
var lst2Odd = 0
for i in lst1 {
if i % 2 == 0 {
lst1Even += 1
}
}
for i in lst2 {
if i % 2 != 0 {
lst2Odd += 1
}
}
if lst1Even == lst1.count && lst2Odd == lst2.count {
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
for (index, value) in lst1.enumerated() {
if value % 2 == 1 {
if lst2.contains(value) {
lst2.remove(at: lst2.firstIndex(of: value)!)
lst1[index] = 0
}
}
}
for value in lst2 {
if value % 2 == 1 {
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
for (index, value) in lst1.enumerated() {
if value % 2 == 1 {
if lst2.contains(value) {
lst2.remove(at: lst2.firstIndex(of: value)!)
lst1[index] = 0
}
}
}
for value in lst2 {
if value % 2 == 1 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
for (index, _) in lst1.enumerated() {
if lst1[index] % 2 == 1 {
lst2.append(lst1[index])
lst1.remove(at: index)
}
}
lst2.sort()
for (index, _) in lst1.enumerated() {
if lst2[index] % 2 == 0 {
lst1.append(lst2[index])
lst2.remove(at: index)
}
}
for (index, _) in lst1.enumerated() {
if lst1[index] % 2 == 1 {
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
for (index, _) in lst1.enumerated() {
if lst1[index] % 2 == 1 {
lst2.append(lst1[index])
lst1.remove(at: index)
}
}
lst2.sort()
for (index, _) in lst1.enumerated() {
if lst2[index] % 2 == 0 {
lst1.append(lst2[index])
lst2.remove(at: index)
}
}
for (index, _) in lst1.enumerated() {
if lst1[index] % 2 == 1 {
return "NO"
}
}
return "YES"
}
```
// Fatal error: Index out of range
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 != 0 {
count += 1
}
}
if count > lst2.count {
return "NO"
}
for i in lst1 {
if i % 2 != 0 {
let index = lst1.firstIndex(of: i)
lst1.remove(at: index!)
lst2.remove(at: index!)
}
}
for i in lst1 {
if i % 2 != 0 {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 != 0 {
count += 1
}
}
if count > lst2.count {
return "NO"
}
for i in lst1 {
if i % 2 != 0 {
let index = lst1.firstIndex(of: i)
lst1.remove(at: index!)
lst2.remove(at: index!)
}
}
for i in lst1 {
if i % 2 != 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
// your code here
var lst1 = lst1
var lst2 = lst2
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 {
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 {
// your code here
var lst1 = lst1
var lst2 = lst2
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 {
return "YES"
} else {
return "NO"
}
}
exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4])
exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4])
```
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 1 {
count += 1
}
}
if count == 0 {
return "YES"
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 1 {
lst1.append(lst2[i])
lst2.remove(at: i)
count -= 1
if count == 0 {
return "YES"
}
}
}
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
}
}
if count == 0 {
return "YES"
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 1 {
lst1.append(lst2[i])
lst2.remove(at: i)
count -= 1
if count == 0 {
return "YES"
}
}
}
return "NO"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
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 == count2 {
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
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 == count2 {
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 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 {
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 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 {
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 {
// Write your code here
var lst1 = lst1
var lst2 = lst2
var lst1Even = [Int]()
var lst2Odd = [Int]()
var lst1Odd = [Int]()
var lst2Even = [Int]()
for i in lst1 {
if i % 2 == 0 {
lst1Even.append(i)
} else {
lst1Odd.append(i)
}
}
for i in lst2 {
if i % 2 == 0 {
lst2Even.append(i)
} else {
lst2Odd.append(i)
}
}
if lst1Even.count == lst1.count {
return "YES"
} else if lst1Odd.count == lst2Even.count && lst2Odd.count == lst1Even.count {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
// Write your code here
var lst1 = lst1
var lst2 = lst2
var lst1Even = [Int]()
var lst2Odd = [Int]()
var lst1Odd = [Int]()
var lst2Even = [Int]()
for i in lst1 {
if i % 2 == 0 {
lst1Even.append(i)
} else {
lst1Odd.append(i)
}
}
for i in lst2 {
if i % 2 == 0 {
lst2Even.append(i)
} else {
lst2Odd.append(i)
}
}
if lst1Even.count == lst1.count {
return "YES"
} else if lst1Odd.count == lst2Even.count && lst2Odd.count == lst1Even.count {
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
func histogram(test: String) -> [String : Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String : Int]'
func histogram(test: String) -> [String : Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String : Int]'
func histogram(test: String) -> [String : Int] {
let words = test.components(separatedBy: " ")
var dict = [String : Int]()
for word in words {
dict[word] = (dict[word] ?? 0) + 1
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let words = test.components(separatedBy: " ")
var dict = [String : Int]()
for word in words {
dict[word] = (dict[word] ?? 0) + 1
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String : Int]'
func histogram(test: String) -> [String : Int] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String : Int]'
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
let words = test.components(separatedBy: " ")
for word in words {
if let count = result[word] {
result[word] = count + 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 let count = result[word] {
result[word] = count + 1
} else {
result[word] = 1
}
}
return result
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let letters = test.components(separatedBy: " ")
for letter in letters {
if let count = dict[letter] {
dict[letter] = count + 1
} else {
dict[letter] = 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 letters = test.components(separatedBy: " ")
for letter in letters {
if let count = dict[letter] {
dict[letter] = count + 1
} else {
dict[letter] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
var arr = test.components(separatedBy: " ")
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
}
var max = 0
var maxKey = ""
for i in dict.keys {
if dict[i]! > max {
max = dict[i]!
maxKey = i
}
}
var result = [String : Int]()
result[maxKey] = max
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 dict = [String : Int]()
var arr = test.components(separatedBy: " ")
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
}
var max = 0
var maxKey = ""
for i in dict.keys {
if dict[i]! > max {
max = dict[i]!
maxKey = i
}
}
var result = [String : Int]()
result[maxKey] = max
return result
}
```
var arr = test.components(separatedBy: " ") // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict: [String : Int] = [:]
let arr = test.split(separator: " ")
for i in arr {
if let count = dict[String(i)] {
dict[String(i)] = count + 1
} else {
dict[String(i)] = 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict: [String : Int] = [:]
let arr = test.split(separator: " ")
for i in arr {
if let count = dict[String(i)] {
dict[String(i)] = count + 1
} else {
dict[String(i)] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String: Int]()
var max = 0
let arr = test.components(separatedBy: " ")
for i in 0..<arr.count {
let key = arr[i]
if let value = dict[key] {
dict[key] = value + 1
} else {
dict[key] = 1
}
if max < dict[key]! {
max = dict[key]!
}
}
var result = [String: Int]()
for (k, v) in dict {
if v == max {
result[k] = v
}
}
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 dict = [String: Int]()
var max = 0
let arr = test.components(separatedBy: " ")
for i in 0..<arr.count {
let key = arr[i]
if let value = dict[key] {
dict[key] = value + 1
} else {
dict[key] = 1
}
if max < dict[key]! {
max = dict[key]!
}
}
var result = [String: Int]()
for (k, v) in dict {
if v == max {
result[k] = v
}
}
return result
}
```
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = s.filter { !c.contains($0) }
return (s, s.reversed() == s)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = s.filter { !c.contains($0) }
return (s, s.reversed() == s)
}
```
return (s, s.reversed() == s) // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
let result = s.filter { !c.contains($0) }
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) {
let result = s.filter { !c.contains($0) }
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
let str = s.filter { !c.contains($0) }
let str1 = String(str.reversed())
return (str, str == str1)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
let str = s.filter { !c.contains($0) }
let str1 = String(str.reversed())
return (str, str == str1)
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s.filter { !c.contains($0) }
let reversed = s.reversed()
var isPalindrome = true
for i in 0..<s.count {
if s[s.index(s.startIndex, offsetBy: i)] != reversed[reversed.index(reversed.startIndex, offsetBy: i)] {
isPalindrome = false
break
}
}
return (s, 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 s = s.filter { !c.contains($0) }
let reversed = s.reversed()
var isPalindrome = true
for i in 0..<s.count {
if s[s.index(s.startIndex, offsetBy: i)] != reversed[reversed.index(reversed.startIndex, offsetBy: i)] {
isPalindrome = false
break
}
}
return (s, isPalindrome)
}
```
var s = s.filter { !c.contains($0) } // variable 's' was never mutated; consider changing to 'let' constant
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = s.filter { !c.contains($0) }
let reversed = String(s.reversed())
return (s, s == 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) {
let s = s.filter { !c.contains($0) }
let reversed = String(s.reversed())
return (s, s == reversed)
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += String(char)
}
}
let reversed = result.reversed()
if String(reversed) == result {
return (result, true)
} else {
return (result, false)
}
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += String(char)
}
}
let reversed = result.reversed()
if String(reversed) == result {
return (result, true)
} else {
return (result, false)
}
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
let result = s.filter { !c.contains($0) }
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) {
let result = s.filter { !c.contains($0) }
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += String(char)
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += String(char)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = s.filter { !c.contains($0) }
return (s, s == String(s.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) {
let s = s.filter { !c.contains($0) }
return (s, s == String(s.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = s.filter { !c.contains($0) }
return (s, s == String(s.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) {
let s = s.filter { !c.contains($0) }
return (s, s == String(s.reversed()))
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
let str = lst[i]
let count = str.filter { $0 == "1" || $0 == "3" || $0 == "5" || $0 == "7" || $0 == "9" }.count
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
let str = lst[i]
let count = str.filter { $0 == "1" || $0 == "3" || $0 == "5" || $0 == "7" || $0 == "9" }.count
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
var count = 0
for j in lst[i] {
if j == "1" || j == "3" || j == "5" || j == "7" || j == "9" {
count += 1
}
}
let str = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
result.append(str)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
var count = 0
for j in lst[i] {
if j == "1" || j == "3" || j == "5" || j == "7" || j == "9" {
count += 1
}
}
let str = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
result.append(str)
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
var count = 0
for j in 0..<lst[i].count {
if Int(String(lst[i][j]))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count) in the string \(count) of the input.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
var count = 0
for j in 0..<lst[i].count {
if Int(String(lst[i][j]))! % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count) in the string \(count) of the input.")
}
return result
}
```
if Int(String(lst[i][j]))! % 2 == 1 { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func oddCount(lst: [String]) -> [String] {
var output: [String] = []
for i in 0..<lst.count {
var count: Int = 0
for char in lst[i] {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
let str = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
output.append(str)
}
return output
}
```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 output: [String] = []
for i in 0..<lst.count {
var count: Int = 0
for char in lst[i] {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
let str = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
output.append(str)
}
return output
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
var count = 0
for j in 0..<lst[i].count {
if lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "1" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "3" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "5" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "7" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "9" {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
var count = 0
for j in 0..<lst[i].count {
if lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "1" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "3" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "5" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "7" || lst[i][lst[i].index(lst[i].startIndex, offsetBy: j)] == "9" {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
let str = lst[i]
let count = str.filter { $0.isLetter }.count
let resultStr = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
result.append(resultStr)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in 0..<lst.count {
let str = lst[i]
let count = str.filter { $0.isLetter }.count
let resultStr = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
result.append(resultStr)
}
return result
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if j != "0" && j != "2" && j != "4" && j != "6" && j != "8" {
count += 1
}
}
let str = "the number of odd elements \(count) in the string \(i) of the input."
result.append(str)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if j != "0" && j != "2" && j != "4" && j != "6" && j != "8" {
count += 1
}
}
let str = "the number of odd elements \(count) in the string \(i) of the input."
result.append(str)
}
return result
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for str in lst {
var count: Int = 0
for char in str {
if char == "1" || char == "3" || char == "5" || char == "7" || char == "9" {
count += 1
}
}
let newStr = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
result.append(newStr)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for str in lst {
var count: Int = 0
for char in str {
if char == "1" || char == "3" || char == "5" || char == "7" || char == "9" {
count += 1
}
}
let newStr = "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
result.append(newStr)
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
let strCount = String(count)
let strStr = String(str)
let strInput = String(lst.count)
let strResult = "the number of odd elements \(strCount)n the str\(strStr)ng \(strStr) of the \(strInput)nput."
result.append(strResult)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
let strCount = String(count)
let strStr = String(str)
let strInput = String(lst.count)
let strResult = "the number of odd elements \(strCount)n the str\(strStr)ng \(strStr) of the \(strInput)nput."
result.append(strResult)
}
return result
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
// TODO: Implement this function
return 0
}
```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 {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
guard nums.count > 0 else { return 0 }
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
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 {
guard nums.count > 0 else { return 0 }
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
guard nums.count > 0 else { return 0 }
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
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 {
guard nums.count > 0 else { return 0 }
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
if sum < minSum { minSum = sum }
if sum > 0 { sum = 0 }
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
for j in i..<nums.count {
let subArray = Array(nums[i...j])
let sum = subArray.reduce(0, +)
minSum = min(minSum, sum)
}
}
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
for i in 0..<nums.count {
for j in i..<nums.count {
let subArray = Array(nums[i...j])
let sum = subArray.reduce(0, +)
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
if nums.isEmpty {
return 0
}
var minSum = nums[0]
var sum = minSum
for i in 1..<nums.count {
if sum < 0 {
sum = 0
}
sum += nums[i]
minSum = min(minSum, sum)
}
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 {
if nums.isEmpty {
return 0
}
var minSum = nums[0]
var sum = minSum
for i in 1..<nums.count {
if sum < 0 {
sum = 0
}
sum += nums[i]
minSum = min(minSum, sum)
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
// TODO: Implement this function
return 0
}
```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 {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
// TODO: Implement this function
return 0
}
```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 {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
if nums.isEmpty {
return 0
}
var minSum = Int.max
var sum = 0
for i in 0 ..< nums.count {
sum += nums[i]
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 {
if nums.isEmpty {
return 0
}
var minSum = Int.max
var sum = 0
for i in 0 ..< nums.count {
sum += nums[i]
minSum = min(minSum, sum)
if sum > 0 {
sum = 0
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
if nums.isEmpty { return 0 }
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = min(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 {
if nums.isEmpty { return 0 }
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = min(sum, 0)
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
if nums.isEmpty { return 0 }
var minSum = nums[0]
var currentSum = minSum
for i in 1..<nums.count {
currentSum = min(currentSum + nums[i], nums[i])
minSum = min(minSum, currentSum)
}
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 {
if nums.isEmpty { return 0 }
var minSum = nums[0]
var currentSum = minSum
for i in 1..<nums.count {
currentSum = min(currentSum + nums[i], nums[i])
minSum = min(minSum, currentSum)
}
return minSum
}
```
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 {
let rows = grid.count
let cols = grid[0].count
var maxFill = 0
for i in 0..<rows {
var currentFill = 0
for j in 0..<cols {
currentFill += grid[i][j]
}
maxFill += min(currentFill, capacity)
}
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 {
let rows = grid.count
let cols = grid[0].count
var maxFill = 0
for i in 0..<rows {
var currentFill = 0
for j in 0..<cols {
currentFill += grid[i][j]
}
maxFill += min(currentFill, capacity)
}
return maxFill
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
var i = 0
var j = 0
while i < grid.count && j < grid[0].count {
if grid[i][j] == 1 {
if capacity > 0 {
grid[i][j] = 0
capacity -= 1
result += 1
} else {
i += 1
capacity = capacity
}
} else {
j += 1
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
var i = 0
var j = 0
while i < grid.count && j < grid[0].count {
if grid[i][j] == 1 {
if capacity > 0 {
grid[i][j] = 0
capacity -= 1
result += 1
} else {
i += 1
capacity = capacity
}
} else {
j += 1
}
}
return result
}
```
capacity = capacity // assigning a variable to itself
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var res = 0
var buckets = Array(repeating: 0, count: m)
for i in stride(from: n - 1, to: -1, by: -1) {
for j in stride(from: m - 1, to: -1, by: -1) {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
for j in stride(from: m - 1, to: -1, by: -1) {
if buckets[j] >= capacity {
buckets[j] -= capacity
res += capacity
} else {
res += buckets[j]
buckets[j] = 0
}
}
}
return res
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var res = 0
var buckets = Array(repeating: 0, count: m)
for i in stride(from: n - 1, to: -1, by: -1) {
for j in stride(from: m - 1, to: -1, by: -1) {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
for j in stride(from: m - 1, to: -1, by: -1) {
if buckets[j] >= capacity {
buckets[j] -= capacity
res += capacity
} else {
res += buckets[j]
buckets[j] = 0
}
}
}
return res
}
```
// XCTAssertTrue failed
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 {
let rows = grid.count
let columns = grid[0].count
var result = 0
var buckets = [Int](repeating: 0, count: columns)
var wells = grid
while true {
var isDone = true
for j in 0..<columns {
if buckets[j] < capacity {
var i = rows - 1
while i >= 0 {
if wells[i][j] == 1 {
buckets[j] += 1
wells[i][j] = 0
break
}
i -= 1
}
if i >= 0 {
isDone = false
}
}
}
if isDone {
break
}
result += 1
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let rows = grid.count
let columns = grid[0].count
var result = 0
var buckets = [Int](repeating: 0, count: columns)
var wells = grid
while true {
var isDone = true
for j in 0..<columns {
if buckets[j] < capacity {
var i = rows - 1
while i >= 0 {
if wells[i][j] == 1 {
buckets[j] += 1
wells[i][j] = 0
break
}
i -= 1
}
if i >= 0 {
isDone = false
}
}
}
if isDone {
break
}
result += 1
}
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
var i = 0
var j = 0
while i < grid.count {
j = 0
while j < grid[i].count {
if grid[i][j] == 1 {
result += capacity
grid[i][j] = 0
j += 1
} else {
j += 1
}
}
i += 1
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
var i = 0
var j = 0
while i < grid.count {
j = 0
while j < grid[i].count {
if grid[i][j] == 1 {
result += capacity
grid[i][j] = 0
j += 1
} else {
j += 1
}
}
i += 1
}
return result
}
```
var capacity = capacity // variable 'capacity' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var row = 0
var col = 0
while row < grid.count && col < grid[0].count {
if grid[row][col] == 1 {
var count = 0
while row < grid.count && grid[row][col] == 1 {
count += 1
row += 1
}
result += count / capacity
if count % capacity == 0 {
col += 1
}
} else {
col += 1
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var row = 0
var col = 0
while row < grid.count && col < grid[0].count {
if grid[row][col] == 1 {
var count = 0
while row < grid.count && grid[row][col] == 1 {
count += 1
row += 1
}
result += count / capacity
if count % capacity == 0 {
col += 1
}
} else {
col += 1
}
}
return result
}
```
var grid = grid // variable 'grid' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var res = 0
var buckets = [Int](repeating: 0, count: m)
var wells = [Int](repeating: 0, count: m)
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
}
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
if buckets[j] == 0 {
res += 1
buckets[j] = capacity
}
buckets[j] -= 1
}
}
}
return res
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var res = 0
var buckets = [Int](repeating: 0, count: m)
var wells = [Int](repeating: 0, count: m)
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
}
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
if buckets[j] == 0 {
res += 1
buckets[j] = capacity
}
buckets[j] -= 1
}
}
}
return res
}
```
var wells = [Int](repeating: 0, count: m) // initialization of variable 'wells' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
var i = 0
while i < grid.count {
var j = 0
while j < grid[i].count {
if grid[i][j] == 1 {
if capacity >= grid[i].count - j {
result += grid[i].count - j
capacity -= grid[i].count - j
grid[i].removeSubrange(j ..< grid[i].count)
} else {
result += capacity
grid[i].removeSubrange(j ..< j + capacity)
capacity = 0
}
} else {
j += 1
}
}
i += 1
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
var i = 0
while i < grid.count {
var j = 0
while j < grid[i].count {
if grid[i][j] == 1 {
if capacity >= grid[i].count - j {
result += grid[i].count - j
capacity -= grid[i].count - j
grid[i].removeSubrange(j ..< grid[i].count)
} else {
result += capacity
grid[i].removeSubrange(j ..< j + capacity)
capacity = 0
}
} else {
j += 1
}
}
i += 1
}
return result
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: {
let count1 = $0.nonzeroBitCount
let count2 = $1.nonzeroBitCount
return count1 == count2 ? $0 < $1 : count1 < count2
})
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: {
let count1 = $0.nonzeroBitCount
let count2 = $1.nonzeroBitCount
return count1 == count2 ? $0 < $1 : count1 < count2
})
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : $0 * -1 }
let arr = arr.map { $0.binaryString().countOnes() }
let arr = arr.sorted(by: <)
return arr
}
```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 arr = arr.map { $0 >= 0 ? $0 : $0 * -1 }
let arr = arr.map { $0.binaryString().countOnes() }
let arr = arr.sorted(by: <)
return arr
}
```
let arr = arr.map { $0.binaryString().countOnes() } // value of type 'Int' has no member 'binaryString'
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : $0 * -1 }
var arr = arr.sorted(by: {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
if a == b {
return $0 > $1
}
return a < b
})
if arr.first! >= 0 {
return arr
}
arr = arr.map { $0 * -1 }
return arr
}
```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 arr = arr.map { $0 >= 0 ? $0 : $0 * -1 }
var arr = arr.sorted(by: {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
if a == b {
return $0 > $1
}
return a < b
})
if arr.first! >= 0 {
return arr
}
arr = arr.map { $0 * -1 }
return arr
}
```
var arr = arr.sorted(by: { // invalid redeclaration of 'arr'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: {
let a = String($0, radix: 2).filter { $0 == "1" }
let b = String($1, radix: 2).filter { $0 == "1" }
if a.count == b.count {
return $0 < $1
}
return a.count < b.count
})
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: {
let a = String($0, radix: 2).filter { $0 == "1" }
let b = String($1, radix: 2).filter { $0 == "1" }
if a.count == b.count {
return $0 < $1
}
return a.count < b.count
})
}
```
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort(by: {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
if a == b {
return $0 > $1
} else {
return a < b
}
})
return arr
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort(by: {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
if a == b {
return $0 > $1
} else {
return a < b
}
})
return arr
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr
sorted.sort {
let first = $0.nonzeroBitCount
let second = $1.nonzeroBitCount
if first == second {
return $0 < $1
}
return first < second
}
return sorted
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr
sorted.sort {
let first = $0.nonzeroBitCount
let second = $1.nonzeroBitCount
if first == second {
return $0 < $1
}
return first < second
}
return sorted
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
if a == b {
return $0 < $1
}
return a < b
}
return arr
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
if a == b {
return $0 < $1
}
return a < b
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -1 * $0 }
let sorted = arr.sorted {
let a = String(format: "%08d", $0)
let b = String(format: "%08d", $1)
return a.filter { $0 == "1" }.count < b.filter { $0 == "1" }.count
|| a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count && $0 < $1
}
return arr.map { $0 >= 0 ? $0 : -1 * $0 }.map { $0 >= 0 ? sorted[$0] : -1 * sorted[$0] }
}
```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 arr = arr.map { $0 >= 0 ? $0 : -1 * $0 }
let sorted = arr.sorted {
let a = String(format: "%08d", $0)
let b = String(format: "%08d", $1)
return a.filter { $0 == "1" }.count < b.filter { $0 == "1" }.count
|| a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count && $0 < $1
}
return arr.map { $0 >= 0 ? $0 : -1 * $0 }.map { $0 >= 0 ? sorted[$0] : -1 * sorted[$0] }
}
```
// Fatal error: Index out of range
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
return a < b || a == b && $0 < $1
}
return arr
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort {
let a = $0.nonzeroBitCount
let b = $1.nonzeroBitCount
return a < b || a == b && $0 < $1
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.map { String($0, radix: 2).map { Int(String($0))! } }
let arr = arr.sorted { $0.filter { $0 == 1 }.count < $1.filter { $0 == 1 }.count }
let arr = arr.map { $0.map { String($0) }.joined() }
let arr = arr.map { Int($0, radix: 2)! }
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
return arr
}
```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 arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.map { String($0, radix: 2).map { Int(String($0))! } }
let arr = arr.sorted { $0.filter { $0 == 1 }.count < $1.filter { $0 == 1 }.count }
let arr = arr.map { $0.map { String($0) }.joined() }
let arr = arr.map { Int($0, radix: 2)! }
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
return arr
}
```
func selectWords(s: String, n: Int) -> [String] {
if s.isEmpty {
return []
}
let words = s.components(separatedBy: " ")
var result: [String] = []
for word in words {
var count = 0
for char in word {
if char.isLetter && !char.isVowel {
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] {
if s.isEmpty {
return []
}
let words = s.components(separatedBy: " ")
var result: [String] = []
for word in words {
var count = 0
for char in word {
if char.isLetter && !char.isVowel {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
```
if char.isLetter && !char.isVowel { // value of type 'Character' has no member 'isVowel'
func selectWords(s: String, n: Int) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
count += 1
}
}
if count == 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 words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
count += 1
}
}
if count == n {
result.append(String(word))
}
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
if s.isEmpty {
return []
}
let words = s.components(separatedBy: " ")
var result: [String] = []
for word in words {
let consonants = word.filter { "aeiouAEIOU".contains($0) == false }
if consonants.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] {
if s.isEmpty {
return []
}
let words = s.components(separatedBy: " ")
var result: [String] = []
for word in words {
let consonants = word.filter { "aeiouAEIOU".contains($0) == false }
if consonants.count == n {
result.append(word)
}
}
return result
}
```
func selectWords(s: String, n: Int) -> [String] {
if s == "" {
return []
}
var words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
count += 1
}
}
if count == 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] {
if s == "" {
return []
}
var words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
count += 1
}
}
if count == n {
result.append(String(word))
}
}
return result
}
```
var words = s.split(separator: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
// your code here
}
```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] {
// your code here
}
```
} // missing return in global function expected to return '[String]'
func selectWords(s: String, n: Int) -> [String] {
if s.isEmpty {
return []
}
var result: [String] = []
var word: [Character] = []
var consonantsCount = 0
for char in s {
if char != " " {
word.append(char)
if "bcdfghjklmnpqrstvwxyz".contains(char) {
consonantsCount += 1
}
if consonantsCount == n {
result.append(String(word))
word.removeAll()
consonantsCount = 0
}
} else {
word.removeAll()
consonantsCount = 0
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
if s.isEmpty {
return []
}
var result: [String] = []
var word: [Character] = []
var consonantsCount = 0
for char in s {
if char != " " {
word.append(char)
if "bcdfghjklmnpqrstvwxyz".contains(char) {
consonantsCount += 1
}
if consonantsCount == n {
result.append(String(word))
word.removeAll()
consonantsCount = 0
}
} else {
word.removeAll()
consonantsCount = 0
}
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
if s == "" {
return []
}
var words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
count += 1
}
}
if count == 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] {
if s == "" {
return []
}
var words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
count += 1
}
}
if count == n {
result.append(String(word))
}
}
return result
}
```
var words = s.split(separator: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
// your code here
if s.isEmpty {
return []
}
var words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if !isVowel(char: char) {
count += 1
}
}
if count == n {
result.append(String(word))
}
}
return result
}
func isVowel(char: Character) -> Bool {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
return true
}
return false
}
```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] {
// your code here
if s.isEmpty {
return []
}
var words = s.split(separator: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if !isVowel(char: char) {
count += 1
}
}
if count == n {
result.append(String(word))
}
}
return result
}
func isVowel(char: Character) -> Bool {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
return true
}
return false
}
```
var words = s.split(separator: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result: [String] = []
for word in words {
if word.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] {
var words = s.components(separatedBy: " ")
var result: [String] = []
for word in words {
if word.count == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var consonants = [Character]()
var vowelsIndex = [Int]()
for (index, char) in word.characters.enumerate() {
if vowels.contains(char.lowercaseString) {
vowelsIndex.append(index)
} else {
consonants.append(char)
}
}
if vowelsIndex.count == 0 {
return ""
}
let lastVowelsIndex = vowelsIndex.last!
let lastVowel = word[word.startIndex.advancedBy(lastVowelsIndex)]
if lastVowelsIndex == word.characters.count - 1 {
return ""
}
let consonantsBetweenVowels = consonants.reverse().enumerate().filter({
$0.index < lastVowelsIndex
})
let consonantsBetweenVowelsCount = consonantsBetweenVowels.count
if consonantsBetweenVowelsCount == 0 {
return ""
}
let lastConsonantIndex = consonantsBetweenVowels[consonantsBetweenVowelsCount - 1].index
let lastConsonant = consonants[lastConsonantIndex]
if consonantsBetweenVowelsCount == 1 {
return String(lastConsonant)
}
let firstConsonantIndex = consonantsBetweenVowels[0].index
let firstConsonant = consonants[firstConsonantIndex]
if lastVowelsIndex - lastConsonantIndex < firstConsonantIndex - lastVowelsIndex {
return String(lastConsonant)
} else {
return String(firstConsonant)
}
}
```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 consonants = [Character]()
var vowelsIndex = [Int]()
for (index, char) in word.characters.enumerate() {
if vowels.contains(char.lowercaseString) {
vowelsIndex.append(index)
} else {
consonants.append(char)
}
}
if vowelsIndex.count == 0 {
return ""
}
let lastVowelsIndex = vowelsIndex.last!
let lastVowel = word[word.startIndex.advancedBy(lastVowelsIndex)]
if lastVowelsIndex == word.characters.count - 1 {
return ""
}
let consonantsBetweenVowels = consonants.reverse().enumerate().filter({
$0.index < lastVowelsIndex
})
let consonantsBetweenVowelsCount = consonantsBetweenVowels.count
if consonantsBetweenVowelsCount == 0 {
return ""
}
let lastConsonantIndex = consonantsBetweenVowels[consonantsBetweenVowelsCount - 1].index
let lastConsonant = consonants[lastConsonantIndex]
if consonantsBetweenVowelsCount == 1 {
return String(lastConsonant)
}
let firstConsonantIndex = consonantsBetweenVowels[0].index
let firstConsonant = consonants[firstConsonantIndex]
if lastVowelsIndex - lastConsonantIndex < firstConsonantIndex - lastVowelsIndex {
return String(lastConsonant)
} else {
return String(firstConsonant)
}
}
```
for (index, char) in word.characters.enumerate() { // value of type 'String' has no member 'enumerate'
let lastVowel = word[word.startIndex.advancedBy(lastVowelsIndex)] // value of type 'String.Index' has no member 'advancedBy'
if lastVowelsIndex == word.characters.count - 1 { // 'characters' is unavailable: Please use String directly
let consonantsBetweenVowels = consonants.reverse().enumerate().filter({ // value of tuple type '()' has no member 'enumerate'
func getClosestVowel(word: String) -> String {
let vowels: [Character] = ["a", "e", "i", "o", "u"]
var consonants: [Character] = []
var vowelsFound: [Character] = []
var closestVowel: Character?
let wordArray: [Character] = Array(word)
for i in 0..<word.count {
if vowels.contains(wordArray[i]) {
vowelsFound.append(wordArray[i])
} else {
consonants.append(wordArray[i])
}
}
if consonants.count > vowelsFound.count {
for i in 0..<consonants.count-1 {
if consonants[i] != consonants[i+1] {
for j in 0..<vowelsFound.count {
if consonants[i+1] == vowelsFound[j] {
closestVowel = vowelsFound[j]
}
}
}
}
}
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: [Character] = ["a", "e", "i", "o", "u"]
var consonants: [Character] = []
var vowelsFound: [Character] = []
var closestVowel: Character?
let wordArray: [Character] = Array(word)
for i in 0..<word.count {
if vowels.contains(wordArray[i]) {
vowelsFound.append(wordArray[i])
} else {
consonants.append(wordArray[i])
}
}
if consonants.count > vowelsFound.count {
for i in 0..<consonants.count-1 {
if consonants[i] != consonants[i+1] {
for j in 0..<vowelsFound.count {
if consonants[i+1] == vowelsFound[j] {
closestVowel = vowelsFound[j]
}
}
}
}
}
return String(closestVowel ?? "")
}
```
return String(closestVowel ?? "") // cannot convert value of type 'String' to expected argument type 'Character'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var consonants = [Character]()
for char in word {
if !vowels.contains(String(char)) {
consonants.append(char)
}
}
var closestVowel = ""
if consonants.count >= 2 {
for i in stride(from: consonants.count - 1, to: 0, by: -1) {
if vowels.contains(String(consonants[i])) {
closestVowel = String(consonants[i])
break
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var consonants = [Character]()
for char in word {
if !vowels.contains(String(char)) {
consonants.append(char)
}
}
var closestVowel = ""
if consonants.count >= 2 {
for i in stride(from: consonants.count - 1, to: 0, by: -1) {
if vowels.contains(String(consonants[i])) {
closestVowel = String(consonants[i])
break
}
}
}
return closestVowel
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
// your code here
let vowels = "aeiouy"
let consonants = "bcdfghjklmnpqrstvwxyz"
var closestVowel = ""
for i in (0...word.count - 1).reversed() {
let char = String(word[word.index(word.startIndex, offsetBy: i)])
if vowels.contains(char) {
closestVowel = char
break
}
}
for i in (0...word.count - 1).reversed() {
let char = String(word[word.index(word.startIndex, offsetBy: i)])
if consonants.contains(char) {
if vowels.contains(char) {
continue
} else {
closestVowel = ""
break
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
// your code here
let vowels = "aeiouy"
let consonants = "bcdfghjklmnpqrstvwxyz"
var closestVowel = ""
for i in (0...word.count - 1).reversed() {
let char = String(word[word.index(word.startIndex, offsetBy: i)])
if vowels.contains(char) {
closestVowel = char
break
}
}
for i in (0...word.count - 1).reversed() {
let char = String(word[word.index(word.startIndex, offsetBy: i)])
if consonants.contains(char) {
if vowels.contains(char) {
continue
} else {
closestVowel = ""
break
}
}
}
return closestVowel
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = word.filter { !vowels.contains($0) }
var vowelIndex = 0
for (index, char) in consonants.enumerated() {
if vowels.contains(String(char)) {
vowelIndex = index
break
}
}
let vowel = consonants[consonants.count - 1 - vowelIndex]
if vowels.contains(vowel) {
return String(vowel)
} 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 {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = word.filter { !vowels.contains($0) }
var vowelIndex = 0
for (index, char) in consonants.enumerated() {
if vowels.contains(String(char)) {
vowelIndex = index
break
}
}
let vowel = consonants[consonants.count - 1 - vowelIndex]
if vowels.contains(vowel) {
return String(vowel)
} else {
return ""
}
}
```
let consonants = word.filter { !vowels.contains($0) } // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
let wordArray = Array(word)
let lastIndex = wordArray.count - 1
var vowelFound = false
var consonantFound = false
var closestVowel = ""
for (index, character) in wordArray.enumerated() {
if vowels.contains(character) {
vowelFound = true
if consonantFound {
closestVowel = String(character)
break
}
}
if consonants.contains(character) {
consonantFound = true
}
if index == lastIndex {
break
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
let wordArray = Array(word)
let lastIndex = wordArray.count - 1
var vowelFound = false
var consonantFound = false
var closestVowel = ""
for (index, character) in wordArray.enumerated() {
if vowels.contains(character) {
vowelFound = true
if consonantFound {
closestVowel = String(character)
break
}
}
if consonants.contains(character) {
consonantFound = true
}
if index == lastIndex {
break
}
}
return closestVowel
}
```
var vowelFound = false // variable 'vowelFound' was written to, but never read
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var closestVowel = ""
for i in (0..<word.count).reversed() {
let char = String(word[word.index(word.startIndex, offsetBy: i)])
if vowels.contains(char) {
closestVowel = char
break
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var closestVowel = ""
for i in (0..<word.count).reversed() {
let char = String(word[word.index(word.startIndex, offsetBy: i)])
if vowels.contains(char) {
closestVowel = char
break
}
}
return closestVowel
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels: [Character] = ["a", "e", "i", "o", "u"]
var consonants: [Character] = []
var vowelsFound: [Character] = []
var closestVowel: Character = Character("")
var closestVowelIndex = Int.max
var wordArray = Array(word)
for i in 0..<wordArray.count {
if vowels.contains(wordArray[i]) {
vowelsFound.append(wordArray[i])
} else {
consonants.append(wordArray[i])
}
}
if consonants.count < 2 || vowelsFound.count == 0 {
return ""
}
for i in 0..<consonants.count-1 {
if consonants[i+1] == vowelsFound[0] {
if i+1 < closestVowelIndex {
closestVowel = consonants[i+1]
closestVowelIndex = i+1
}
}
}
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: [Character] = ["a", "e", "i", "o", "u"]
var consonants: [Character] = []
var vowelsFound: [Character] = []
var closestVowel: Character = Character("")
var closestVowelIndex = Int.max
var wordArray = Array(word)
for i in 0..<wordArray.count {
if vowels.contains(wordArray[i]) {
vowelsFound.append(wordArray[i])
} else {
consonants.append(wordArray[i])
}
}
if consonants.count < 2 || vowelsFound.count == 0 {
return ""
}
for i in 0..<consonants.count-1 {
if consonants[i+1] == vowelsFound[0] {
if i+1 < closestVowelIndex {
closestVowel = consonants[i+1]
closestVowelIndex = i+1
}
}
}
return String(closestVowel)
}
```
var wordArray = Array(word) // variable 'wordArray' was never mutated; consider changing to 'let' constant
// Fatal error: Can't form a Character from an empty String
func getClosestVowel(word: String) -> String {
let vowels: [Character] = ["a", "e", "i", "o", "u"]
let consonants: [Character] = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var closestVowel: Character = Character("")
var closestVowelIndex: Int = -1
var closestVowelDistance: Int = -1
var vowelIndex: Int = -1
var consonantIndex: Int = -1
let wordArray = Array(word)
for (index, character) in wordArray.enumerated() {
if vowels.contains(character) {
vowelIndex = index
for (consonantIndex, character) in wordArray.enumerated() {
if consonants.contains(character) {
if vowelIndex > consonantIndex {
let distance = vowelIndex - consonantIndex
if distance > closestVowelDistance {
closestVowel = character
closestVowelDistance = distance
closestVowelIndex = consonantIndex
}
}
}
}
}
}
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: [Character] = ["a", "e", "i", "o", "u"]
let consonants: [Character] = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var closestVowel: Character = Character("")
var closestVowelIndex: Int = -1
var closestVowelDistance: Int = -1
var vowelIndex: Int = -1
var consonantIndex: Int = -1
let wordArray = Array(word)
for (index, character) in wordArray.enumerated() {
if vowels.contains(character) {
vowelIndex = index
for (consonantIndex, character) in wordArray.enumerated() {
if consonants.contains(character) {
if vowelIndex > consonantIndex {
let distance = vowelIndex - consonantIndex
if distance > closestVowelDistance {
closestVowel = character
closestVowelDistance = distance
closestVowelIndex = consonantIndex
}
}
}
}
}
}
return String(closestVowel)
}
```
var closestVowelIndex: Int = -1 // variable 'closestVowelIndex' was written to, but never read
var consonantIndex: Int = -1 // variable 'consonantIndex' was never used; consider replacing with '_' or removing it
// Fatal error: Can't form a Character from an empty String
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var consonants = [String]()
var vowelsIndex = [Int]()
for (index, character) in word.enumerated() {
if vowels.contains(String(character).lowercased()) {
vowelsIndex.append(index)
} else {
consonants.append(String(character))
}
}
if consonants.count < 2 || vowelsIndex.count < 2 {
return ""
}
var closestVowelIndex = vowelsIndex[vowelsIndex.count - 2]
for i in 0 ..< consonants.count - 1 {
if consonants[i] != consonants[i + 1] {
closestVowelIndex = vowelsIndex[vowelsIndex.count - 2]
break
}
}
return String(word[word.index(word.startIndex, offsetBy: closestVowelIndex)])
}
```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 consonants = [String]()
var vowelsIndex = [Int]()
for (index, character) in word.enumerated() {
if vowels.contains(String(character).lowercased()) {
vowelsIndex.append(index)
} else {
consonants.append(String(character))
}
}
if consonants.count < 2 || vowelsIndex.count < 2 {
return ""
}
var closestVowelIndex = vowelsIndex[vowelsIndex.count - 2]
for i in 0 ..< consonants.count - 1 {
if consonants[i] != consonants[i + 1] {
closestVowelIndex = vowelsIndex[vowelsIndex.count - 2]
break
}
}
return String(word[word.index(word.startIndex, offsetBy: closestVowelIndex)])
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'String'
func matchParens(lst: [String]) -> String {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'String'
func matchParens(lst: [String]) -> String {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'String'
func matchParens(lst: [String]) -> String {
var count = 0
for str in lst {
if str == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
return count == 0 ? "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 count = 0
for str in lst {
if str == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
return count == 0 ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var openCount = 0
var closeCount = 0
for str in lst {
if str == "(" {
openCount += 1
} else {
closeCount += 1
}
}
if openCount == closeCount {
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 openCount = 0
var closeCount = 0
for str in lst {
if str == "(" {
openCount += 1
} else {
closeCount += 1
}
}
if openCount == closeCount {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
return count == 0 ? "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 count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
return count == 0 ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var openCount = 0
var closeCount = 0
for str in lst {
for char in str {
if char == "(" {
openCount += 1
} else {
closeCount += 1
}
}
}
if openCount == closeCount {
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 openCount = 0
var closeCount = 0
for str in lst {
for char in str {
if char == "(" {
openCount += 1
} else {
closeCount += 1
}
}
}
if openCount == closeCount {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
let open = lst.filter { $0 == "(" }.count
let close = lst.filter { $0 == ")" }.count
return open == close ? "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 {
let open = lst.filter { $0 == "(" }.count
let close = lst.filter { $0 == ")" }.count
return open == close ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for str in lst {
if str == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
return count == 0 ? "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 count = 0
for str in lst {
if str == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
return count == 0 ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
let open = lst.filter { $0 == "(" }.count
let close = lst.filter { $0 == ")" }.count
if open == close {
return "Yes"
}
return "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
let open = lst.filter { $0 == "(" }.count
let close = lst.filter { $0 == ")" }.count
if open == close {
return "Yes"
}
return "No"
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in arr {
dict[i] = (dict[i] ?? 0) + 1
}
let sortedDict = dict.sorted { $0.key > $1.key }
for (i, j) in sortedDict {
if k == 0 {
break
}
for _ in 0..<j {
if k == 0 {
break
}
result.append(i)
k -= 1
}
}
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 dict = [Int: Int]()
for i in arr {
dict[i] = (dict[i] ?? 0) + 1
}
let sortedDict = dict.sorted { $0.key > $1.key }
for (i, j) in sortedDict {
if k == 0 {
break
}
for _ in 0..<j {
if k == 0 {
break
}
result.append(i)
k -= 1
}
}
return result
}
```
k -= 1 // left side of mutating operator isn't mutable: 'k' is a 'let' constant
func maximum(arr: [Int], k: Int) -> [Int] {
var result: [Int] = []
var arr = arr
for _ in 0..<k {
let max = arr.max() ?? 0
arr.removeAll(where: {$0 == max})
result.append(max)
}
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 arr = arr
for _ in 0..<k {
let max = arr.max() ?? 0
arr.removeAll(where: {$0 == max})
result.append(max)
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result: [Int] = []
var count = 0
for i in arr {
if count < k {
result.append(i)
count += 1
} else {
for j in 0...result.count-1 {
if result[j] < i {
result.insert(i, at: j)
result.removeLast()
break
}
}
}
}
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 count = 0
for i in arr {
if count < k {
result.append(i)
count += 1
} else {
for j in 0...result.count-1 {
if result[j] < i {
result.insert(i, at: j)
result.removeLast()
break
}
}
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result: [Int] = []
var maxHeap: [Int] = []
for i in 0..<k {
maxHeap.append(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap[0] {
maxHeap[0] = arr[i]
maxHeap = heapify(arr: maxHeap)
}
}
for i in 0..<k {
result.append(maxHeap[0])
maxHeap[0] = maxHeap[maxHeap.count - 1]
maxHeap.removeLast()
maxHeap = heapify(arr: maxHeap)
}
return result.sorted(by: <)
}
func heapify(arr: [Int]) -> [Int] {
var result = arr
for i in 0..<result.count {
result = heapify(arr: result, i: i)
}
return result
}
func heapify(arr: [Int], i: Int) -> [Int] {
var result = arr
var parent = i
var child = 2 * i + 1
while child < result.count {
if child + 1 < result.count && result[child] < result[child + 1] {
child += 1
}
if result[child] > result[parent] {
result.swapAt(child, parent)
parent = child
child = 2 * parent + 1
} else {
break
}
}
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 maxHeap: [Int] = []
for i in 0..<k {
maxHeap.append(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap[0] {
maxHeap[0] = arr[i]
maxHeap = heapify(arr: maxHeap)
}
}
for i in 0..<k {
result.append(maxHeap[0])
maxHeap[0] = maxHeap[maxHeap.count - 1]
maxHeap.removeLast()
maxHeap = heapify(arr: maxHeap)
}
return result.sorted(by: <)
}
func heapify(arr: [Int]) -> [Int] {
var result = arr
for i in 0..<result.count {
result = heapify(arr: result, i: i)
}
return result
}
func heapify(arr: [Int], i: Int) -> [Int] {
var result = arr
var parent = i
var child = 2 * i + 1
while child < result.count {
if child + 1 < result.count && result[child] < result[child + 1] {
child += 1
}
if result[child] > result[parent] {
result.swapAt(child, parent)
parent = child
child = 2 * parent + 1
} else {
break
}
}
return result
}
```
for i in 0..<k { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var sortedArr = arr.sorted(by: {$0 < $1})
for _ in 0..<k {
result.append(sortedArr.removeLast())
}
return result.sorted(by: {$0 > $1})
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var sortedArr = arr.sorted(by: {$0 < $1})
for _ in 0..<k {
result.append(sortedArr.removeLast())
}
return result.sorted(by: {$0 > $1})
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var count = 0
for i in arr {
if count < k {
result.append(i)
count += 1
} else {
if i > result.min()! {
result.removeLast()
result.append(i)
}
}
}
return result.sorted(by: >)
}
```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 count = 0
for i in arr {
if count < k {
result.append(i)
count += 1
} else {
if i > result.min()! {
result.removeLast()
result.append(i)
}
}
}
return result.sorted(by: >)
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result: [Int] = []
var arr = arr
var i = 0
while i < k {
if arr.isEmpty {
break
}
var max = arr[0]
var maxIndex = 0
for (index, value) in arr.enumerated() {
if value > max {
max = value
maxIndex = index
}
}
result.append(max)
arr.remove(at: maxIndex)
i += 1
}
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 arr = arr
var i = 0
while i < k {
if arr.isEmpty {
break
}
var max = arr[0]
var maxIndex = 0
for (index, value) in arr.enumerated() {
if value > max {
max = value
maxIndex = index
}
}
result.append(max)
arr.remove(at: maxIndex)
i += 1
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr.sorted()
var result = [Int]()
for i in 0..<k {
if i >= arr.count {
break
}
result.append(arr[arr.count - 1 - i])
}
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 arr = arr.sorted()
var result = [Int]()
for i in 0..<k {
if i >= arr.count {
break
}
result.append(arr[arr.count - 1 - i])
}
return result
}
```
var arr = arr.sorted() // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var temp = [Int]()
var count = 0
for i in arr {
if count < k {
temp.append(i)
count += 1
} else {
if i > temp.min()! {
temp.remove(at: temp.firstIndex(of: temp.min()!)!)
temp.append(i)
}
}
}
result = temp.sorted()
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 temp = [Int]()
var count = 0
for i in arr {
if count < k {
temp.append(i)
count += 1
} else {
if i > temp.min()! {
temp.remove(at: temp.firstIndex(of: temp.min()!)!)
temp.append(i)
}
}
}
result = temp.sorted()
return result
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func maximum(arr: [Int], k: Int) -> [Int] {
var result: [Int] = []
var count = 0
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
var arr2 = arr
while count < k {
for i in 0..<arr2.count {
if arr2[i] == max {
result.append(arr2[i])
arr2.remove(at: i)
max = 0
count += 1
break
}
}
for i in 0..<arr2.count {
if arr2[i] > max {
max = arr2[i]
}
}
}
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 count = 0
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
var arr2 = arr
while count < k {
for i in 0..<arr2.count {
if arr2[i] == max {
result.append(arr2[i])
arr2.remove(at: i)
max = 0
count += 1
break
}
}
for i in 0..<arr2.count {
if arr2[i] > max {
max = arr2[i]
}
}
}
return result
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, element) in lst.enumerated() {
if index % 2 == 0 && element % 2 != 0 {
sum += element
}
}
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, element) in lst.enumerated() {
if index % 2 == 0 && element % 2 != 0 {
sum += element
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.filter { $0 % 2 != 0 }.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 }.filter { $0 % 2 != 0 }.reduce(0, +)
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for (i, value) in lst.enumerated() {
if i % 2 == 0 && value % 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 (i, value) in lst.enumerated() {
if i % 2 == 0 && value % 2 != 0 {
sum += value
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 }.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.filter { $0 % 2 == 0 }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (i, n) in lst.enumerated() {
if i % 2 == 0 && n % 2 != 0 {
sum += n
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (i, n) in lst.enumerated() {
if i % 2 == 0 && n % 2 != 0 {
sum += n
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 1 }.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.filter { $0 % 2 == 1 }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for (i, num) in lst.enumerated() {
if i % 2 == 0 && num % 2 != 0 {
sum += num
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (i, num) in lst.enumerated() {
if i % 2 == 0 && num % 2 != 0 {
sum += num
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter({$0.offset % 2 == 0}).filter({$0.element % 2 == 1}).reduce(0, { $0 + $1.element })
}
```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}).filter({$0.element % 2 == 1}).reduce(0, { $0 + $1.element })
}
```
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }.filter { $0 % 2 == 1 }.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 }.filter { $0 % 2 == 1 }.reduce(0, +)
}
```
func solution(lst: [Int]) -> Int {
return lst.enumerated().filter({$0.offset % 2 == 0 }).map({$0.element}).filter({$0 % 2 == 1}).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}).filter({$0 % 2 == 1}).reduce(0, +)
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num >= 100 && num <= 999 {
sum += num
} else if num >= 10 && num <= 99 {
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 && num <= 999 {
sum += num
} else if num >= 10 && num <= 99 {
sum += num
}
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num >= 100 && num <= 999 {
sum += num
} else if num >= 10 && num <= 99 {
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 && num <= 999 {
sum += num
} else if num >= 10 && num <= 99 {
sum += num
}
}
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 || num < 10 {
continue
}
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 || num < 10 {
continue
}
sum += num
}
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 {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
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 {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
collatz = collatz.filter { $0 % 2 != 0 }
return collatz.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 collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
collatz = collatz.filter { $0 % 2 != 0 }
return collatz.sorted()
}
```
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
collatz.append(current)
}
collatz.reverse()
return collatz.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
collatz.append(current)
}
collatz.reverse()
return collatz.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var number = n
while number != 1 {
if number % 2 == 0 {
number = number / 2
} else {
number = (number * 3) + 1
}
collatz.append(number)
}
return collatz.filter { $0 % 2 != 0 }.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 collatz = [Int]()
var number = n
while number != 1 {
if number % 2 == 0 {
number = number / 2
} else {
number = (number * 3) + 1
}
collatz.append(number)
}
return collatz.filter { $0 % 2 != 0 }.sorted()
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = 3 * current + 1
}
if current % 2 != 0 {
collatz.append(current)
}
}
return collatz
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = 3 * current + 1
}
if current % 2 != 0 {
collatz.append(current)
}
}
return collatz
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [n]
var i = n
while i != 1 {
if i % 2 == 0 {
i /= 2
} else {
i = i * 3 + 1
}
arr.append(i)
}
return arr.filter { $0 % 2 != 0 }
}
```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 arr = [n]
var i = n
while i != 1 {
if i % 2 == 0 {
i /= 2
} else {
i = i * 3 + 1
}
arr.append(i)
}
return arr.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var num = n
while num != 1 {
collatz.append(num)
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var num = n
while num != 1 {
collatz.append(num)
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
collatz.append(current)
}
collatz.reverse()
let oddCollatz = collatz.filter { $0 % 2 == 1 }
return oddCollatz
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
collatz.append(current)
}
collatz.reverse()
let oddCollatz = collatz.filter { $0 % 2 == 1 }
return oddCollatz
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var number = n
while number != 1 {
result.append(number)
number = number % 2 == 0 ? number / 2 : 3 * number + 1
}
result.append(1)
return result.filter { $0 % 2 != 0 }
}
```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 number = n
while number != 1 {
result.append(number)
number = number % 2 == 0 ? number / 2 : 3 * number + 1
}
result.append(1)
return result.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
collatz = collatz.filter { $0 % 2 != 0 }
return collatz
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
collatz = collatz.filter { $0 % 2 != 0 }
return collatz
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
guard dateArray.count == 3 else {
return false
}
guard let month = Int(dateArray[0]),
let day = Int(dateArray[1]),
let year = Int(dateArray[2]) else {
return false
}
guard month > 0, month <= 12, day > 0, day <= 31, year > 0 else {
return false
}
if month == 2 {
if year % 4 == 0 && year % 100 != 0 || year % 400 == 0 {
return day <= 29
} else {
return day <= 28
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
return day <= 30
} else {
return true
}
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
guard dateArray.count == 3 else {
return false
}
guard let month = Int(dateArray[0]),
let day = Int(dateArray[1]),
let year = Int(dateArray[2]) else {
return false
}
guard month > 0, month <= 12, day > 0, day <= 31, year > 0 else {
return false
}
if month == 2 {
if year % 4 == 0 && year % 100 != 0 || year % 400 == 0 {
return day <= 29
} else {
return day <= 28
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
return day <= 30
} else {
return true
}
}
```
func validDate(date: String) -> Bool {
let date = date.components(separatedBy: "-")
if date.count == 3 {
let month = Int(date[0])!
let day = Int(date[1])!
let year = Int(date[2])!
if month > 12 || month < 1 {
return false
}
if month == 2 && day > 29 {
return false
}
if day > 31 || day < 1 {
return false
}
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day > 31 {
return false
}
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
} else {
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 date = date.components(separatedBy: "-")
if date.count == 3 {
let month = Int(date[0])!
let day = Int(date[1])!
let year = Int(date[2])!
if month > 12 || month < 1 {
return false
}
if month == 2 && day > 29 {
return false
}
if day > 31 || day < 1 {
return false
}
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day > 31 {
return false
}
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
} else {
return false
}
}
```
let year = Int(date[2])! // initialization of immutable value 'year' was never used; consider replacing with assignment to '_' or removing it
func validDate(date: String) -> Bool {
let dateArray = date.components(separatedBy: "-")
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if dateArray.count != 3 {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.components(separatedBy: "-")
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if dateArray.count != 3 {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.components(separatedBy: "-")
if date.count == 3 {
let month = Int(date[0]) ?? 0
let day = Int(date[1]) ?? 0
let year = Int(date[2]) ?? 0
if month < 1 || month > 12 {
return false
} else if day < 1 || day > 31 {
return false
} else if year < 1 {
return false
} else if month == 2 && day > 29 {
return false
} else if (month == 4 || month == 6 || month == 9 || month == 11) && day > 30 {
return false
}
} else {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.components(separatedBy: "-")
if date.count == 3 {
let month = Int(date[0]) ?? 0
let day = Int(date[1]) ?? 0
let year = Int(date[2]) ?? 0
if month < 1 || month > 12 {
return false
} else if day < 1 || day > 31 {
return false
} else if year < 1 {
return false
} else if month == 2 && day > 29 {
return false
} else if (month == 4 || month == 6 || month == 9 || month == 11) && day > 30 {
return false
}
} else {
return false
}
return true
}
```
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 || day < 1 || day > 31 || year < 1 {
return false
}
if month == 2 {
if year % 4 == 0 {
if day > 29 {
return false
}
} else {
if day > 28 {
return false
}
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 || day < 1 || day > 31 || year < 1 {
return false
}
if month == 2 {
if year % 4 == 0 {
if day > 29 {
return false
}
} else {
if day > 28 {
return false
}
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let dateComponents = date.split(separator: "-")
guard dateComponents.count == 3 else { return false }
let month = Int(dateComponents[0]) ?? 0
let day = Int(dateComponents[1]) ?? 0
let year = Int(dateComponents[2]) ?? 0
let isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
if month < 1 || month > 12 || day < 1 || day > 31 || year < 1 { return false }
if month == 2 {
if isLeapYear && day > 29 { return false }
if !isLeapYear && day > 28 { return false }
}
if [4, 6, 9, 11].contains(month) && day > 30 { return false }
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateComponents = date.split(separator: "-")
guard dateComponents.count == 3 else { return false }
let month = Int(dateComponents[0]) ?? 0
let day = Int(dateComponents[1]) ?? 0
let year = Int(dateComponents[2]) ?? 0
let isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
if month < 1 || month > 12 || day < 1 || day > 31 || year < 1 { return false }
if month == 2 {
if isLeapYear && day > 29 { return false }
if !isLeapYear && day > 28 { return false }
}
if [4, 6, 9, 11].contains(month) && day > 30 { return false }
return true
}
```
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
guard date.count == 3 else { return false }
guard let month = Int(date[0]), month > 0, month <= 12 else { return false }
guard let day = Int(date[1]), day > 0, day <= 31 else { return false }
guard let year = Int(date[2]), year > 0 else { return false }
if month == 2 && day > 29 { return false }
if [1, 3, 5, 7, 8, 10, 12].contains(month) && day > 31 { return false }
if [4, 6, 9, 11].contains(month) && day > 30 { return false }
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
guard date.count == 3 else { return false }
guard let month = Int(date[0]), month > 0, month <= 12 else { return false }
guard let day = Int(date[1]), day > 0, day <= 31 else { return false }
guard let year = Int(date[2]), year > 0 else { return false }
if month == 2 && day > 29 { return false }
if [1, 3, 5, 7, 8, 10, 12].contains(month) && day > 31 { return false }
if [4, 6, 9, 11].contains(month) && day > 30 { return false }
return true
}
```
func validDate(date: String) -> Bool {
let dateComponents = date.components(separatedBy: "-")
guard dateComponents.count == 3 else {
return false
}
let month = Int(dateComponents[0]) ?? 0
let day = Int(dateComponents[1]) ?? 0
let year = Int(dateComponents[2]) ?? 0
guard month >= 1 && month <= 12 else {
return false
}
guard day >= 1 && day <= 31 else {
return false
}
guard year >= 1 else {
return false
}
if month == 2 && day <= 29 {
return true
} else if month == 2 && day > 29 {
return false
} else if month == 4 || month == 6 || month == 9 || month == 11 && day <= 30 {
return true
} else if month == 4 || month == 6 || month == 9 || month == 11 && day > 30 {
return false
} else {
return true
}
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateComponents = date.components(separatedBy: "-")
guard dateComponents.count == 3 else {
return false
}
let month = Int(dateComponents[0]) ?? 0
let day = Int(dateComponents[1]) ?? 0
let year = Int(dateComponents[2]) ?? 0
guard month >= 1 && month <= 12 else {
return false
}
guard day >= 1 && day <= 31 else {
return false
}
guard year >= 1 else {
return false
}
if month == 2 && day <= 29 {
return true
} else if month == 2 && day > 29 {
return false
} else if month == 4 || month == 6 || month == 9 || month == 11 && day <= 30 {
return true
} else if month == 4 || month == 6 || month == 9 || month == 11 && day > 30 {
return false
} else {
return true
}
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
let month = Int(dateArray[0]) ?? 0
let day = Int(dateArray[1]) ?? 0
let year = Int(dateArray[2]) ?? 0
if month == 0 || day == 0 || year == 0 {
return false
}
if month < 1 || month > 12 {
return false
}
if day < 1 || day > 31 {
return false
}
if month == 2 && day > 29 {
return false
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
let month = Int(dateArray[0]) ?? 0
let day = Int(dateArray[1]) ?? 0
let year = Int(dateArray[2]) ?? 0
if month == 0 || day == 0 || year == 0 {
return false
}
if month < 1 || month > 12 {
return false
}
if day < 1 || day > 31 {
return false
}
if month == 2 && day > 29 {
return false
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let dateComponents = date.components(separatedBy: "-")
guard dateComponents.count == 3 else { return false }
let month = Int(dateComponents[0]) ?? 0
let day = Int(dateComponents[1]) ?? 0
let year = Int(dateComponents[2]) ?? 0
if month < 1 || month > 12 { return false }
if day < 1 || day > 31 { return false }
if year < 1 { return false }
if month == 2 {
if day > 29 { return false }
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 { return false }
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateComponents = date.components(separatedBy: "-")
guard dateComponents.count == 3 else { return false }
let month = Int(dateComponents[0]) ?? 0
let day = Int(dateComponents[1]) ?? 0
let year = Int(dateComponents[2]) ?? 0
if month < 1 || month > 12 { return false }
if day < 1 || day > 31 { return false }
if year < 1 { return false }
if month == 2 {
if day > 29 { return false }
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 { return false }
}
return true
}
```
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> {
let words = txt.components(separatedBy: " ")
let words2 = txt.components(separatedBy: ",")
if words.count > 1 {
return .success(words)
} else if words2.count > 1 {
return .success(words2)
} else {
return .failure(oddLetters(txt: txt))
}
}
func oddLetters(txt: String) -> Int {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var count = 0
for letter in txt {
let index = alphabet.firstIndex(of: letter)!
if index % 2 != 0 {
count += 1
}
}
return count
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
let words2 = txt.components(separatedBy: ",")
if words.count > 1 {
return .success(words)
} else if words2.count > 1 {
return .success(words2)
} else {
return .failure(oddLetters(txt: txt))
}
}
// Given a string of lower-case letters, return the number of lower-case letters with odd order in the alphabet,
// ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// oddLetters(txt: "abcdef") == 3
// oddLetters(txt: "az") == 1
// oddLetters(txt: "z") == 0
func oddLetters(txt: String) -> Int {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var count = 0
for letter in txt {
let index = alphabet.firstIndex(of: letter)!
if index % 2 != 0 {
count += 1
}
}
return count
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
if index % 2 != 0 { // cannot convert value of type 'String.Index' to expected argument type 'Int'
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> {
let words = txt.split(separator: " ")
if words.count > 1 {
return .success(words.map(String.init))
} else {
let chars = txt.split(separator: ",")
if chars.count > 1 {
return .success(chars.map(String.init))
} else {
let count = txt.reduce(0) { $0 + ($1.isLowercase && $1.asciiValue! % 2 == 1 ? 1 : 0) }
return .failure(count)
}
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count > 1 {
return .success(words.map(String.init))
} else {
let chars = txt.split(separator: ",")
if chars.count > 1 {
return .success(chars.map(String.init))
} else {
let count = txt.reduce(0) { $0 + ($1.isLowercase && $1.asciiValue! % 2 == 1 ? 1 : 0) }
return .failure(count)
}
}
}
```
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> {
// your code here
}
```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> {
// your code here
}
```
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> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
var count = 0
for char in txt {
if char.isLowercase {
if char.asciiValue! % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
var count = 0
for char in txt {
if char.isLowercase {
if char.asciiValue! % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
}
```
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> {
let words = txt.components(separatedBy: .whitespacesAndNewlines)
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
return .failure(txt.lowercased().filter { $0.isLetter && $0.asciiValue! % 2 == 1 }.count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: .whitespacesAndNewlines)
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
return .failure(txt.lowercased().filter { $0.isLetter && $0.asciiValue! % 2 == 1 }.count)
}
```
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> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.components(separatedBy: " "))
}
if let _ = txt.range(of: ",") {
return .success(txt.components(separatedBy: ","))
}
var count = 0
for (index, char) in txt.enumerated() {
if char.isLowercase {
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.components(separatedBy: " "))
}
if let _ = txt.range(of: ",") {
return .success(txt.components(separatedBy: ","))
}
var count = 0
for (index, char) in txt.enumerated() {
if char.isLowercase {
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.components(separatedBy: " "))
}
if let _ = txt.range(of: ",") {
return .success(txt.components(separatedBy: ","))
}
var count = 0
for (index, char) in txt.enumerated() {
if char.isLowercase {
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.components(separatedBy: " "))
}
if let _ = txt.range(of: ",") {
return .success(txt.components(separatedBy: ","))
}
var count = 0
for (index, char) in txt.enumerated() {
if char.isLowercase {
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
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> {
// your code here
let words = txt.components(separatedBy: .whitespacesAndNewlines)
if words.isEmpty {
return .failure(0)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
let count = txt.lowercased().filter { $0.isLetter && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
// your code here
let words = txt.components(separatedBy: .whitespacesAndNewlines)
if words.isEmpty {
return .failure(0)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
let count = txt.lowercased().filter { $0.isLetter && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
```
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> {
if txt.contains(" ") {
return .success(txt.components(separatedBy: " "))
} else if txt.contains(",") {
return .success(txt.components(separatedBy: ","))
} else {
let count = txt.filter { $0.isLowercase }.map { $0.asciiValue! - 97 }.filter { $0 % 2 != 0 }.count
return .failure(count)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.components(separatedBy: " "))
} else if txt.contains(",") {
return .success(txt.components(separatedBy: ","))
} else {
let count = txt.filter { $0.isLowercase }.map { $0.asciiValue! - 97 }.filter { $0 % 2 != 0 }.count
return .failure(count)
}
}
```
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> {
// your code here
}
```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> {
// your code here
}
```
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> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.split(separator: " "))
} else if let _ = txt.rangeOfCharacter(from: CharacterSet.decimalDigits) {
return .success(txt.split(separator: ","))
} else {
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 })
}
}
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.split(separator: " "))
} else if let _ = txt.rangeOfCharacter(from: CharacterSet.decimalDigits) {
return .success(txt.split(separator: ","))
} else {
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 })
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.split(separator: " "))
} else if let _ = txt.rangeOfCharacter(from: CharacterSet.decimalDigits) {
return .success(txt.split(separator: ","))
} else {
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 })
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.split(separator: " "))
} else if let _ = txt.rangeOfCharacter(from: CharacterSet.decimalDigits) {
return .success(txt.split(separator: ","))
} else {
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 })
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.split(separator: " "))
} else if let _ = txt.rangeOfCharacter(from: CharacterSet.decimalDigits) {
return .success(txt.split(separator: ","))
} else {
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 })
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if let _ = txt.rangeOfCharacter(from: CharacterSet.whitespaces) {
return .success(txt.split(separator: " "))
} else if let _ = txt.rangeOfCharacter(from: CharacterSet.decimalDigits) {
return .success(txt.split(separator: ","))
} else {
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 })
}
}
// 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
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return .success(txt.split(separator: " ")) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
return .success(txt.split(separator: ",")) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 }) // cannot convert value of type 'UInt32' to expected argument type 'Int'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
return .success(txt.split(separator: " ")) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
return .success(txt.split(separator: ",")) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
return .failure(txt.lowercased().reduce(0) { $0 + $1.unicodeScalars.first!.value % 2 }) // cannot convert value of type 'UInt32' to expected argument type 'Int'
func isSorted(lst: [Int]) -> Bool {
var sorted = lst.sorted()
if lst == sorted {
return true
}
return false
}
```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 = lst.sorted()
if lst == sorted {
return true
}
return false
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0 ..< lst.count-1 {
if lst[i] > lst[i+1] {
sorted = false
break
}
}
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
break
}
}
return sorted
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var previous = lst[0]
for i in 1..<lst.count {
if lst[i] < previous {
sorted = false
break
}
previous = lst[i]
}
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
var previous = lst[0]
for i in 1..<lst.count {
if lst[i] < previous {
sorted = false
break
}
previous = lst[i]
}
return sorted
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
var sorted = lst
sorted.sort()
return sorted == lst
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = lst
sorted.sort()
return sorted == lst
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
sorted = false
break
}
last = lst[i]
}
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
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
sorted = false
break
}
last = lst[i]
}
return sorted
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var i = 1
while i < lst.count && sorted {
if lst[i] < lst[i - 1] {
sorted = false
}
i += 1
}
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
var i = 1
while i < lst.count && sorted {
if lst[i] < lst[i - 1] {
sorted = false
}
i += 1
}
return sorted
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = lst.sorted()
var i = 0
while i < sorted.count {
if lst[i] != sorted[i] {
return false
}
i += 1
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = lst.sorted()
var i = 0
while i < sorted.count {
if lst[i] != sorted[i] {
return false
}
i += 1
}
return true
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = lst
sorted.sort()
return sorted == lst
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = lst
sorted.sort()
return sorted == lst
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var count = 0
for i in 0..<lst.count {
if lst[i] > lst[i+1] {
sorted = false
break
}
}
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
var count = 0
for i in 0..<lst.count {
if lst[i] > lst[i+1] {
sorted = false
break
}
}
return sorted
}
```
var count = 0 // initialization of variable 'count' was never used; consider replacing with assignment to '_' or removing it
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
var sorted = lst.sorted()
return lst == 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 = lst.sorted()
return lst == sorted
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (start, end) = (max(start1, start2), min(end1, end2))
let length = end - start
return length > 0 ? (length > 1 && (2...(length/2)).allSatisfy({ length % $0 != 0 }) ? "YES" : "NO") : "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, end) = (max(start1, start2), min(end1, end2))
let length = end - start
return length > 0 ? (length > 1 && (2...(length/2)).allSatisfy({ length % $0 != 0 }) ? "YES" : "NO") : "NO"
}
```
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (minStart, maxEnd) = (max(start1, start2), min(end1, end2))
if minStart > maxEnd {
return "NO"
}
let length = maxEnd - minStart + 1
return length > 1 && isPrime(length) ? "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 (minStart, maxEnd) = (max(start1, start2), min(end1, end2))
if minStart > maxEnd {
return "NO"
}
let length = maxEnd - minStart + 1
return length > 1 && isPrime(length) ? "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
}
```
// XCTAssertTrue failed
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)
if (start == end) {
return "NO"
}
let length = end - start
for i in 2...length {
if (length % i == 0) {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if (start1 > end2 || start2 > end1) {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
if (start == end) {
return "NO"
}
let length = end - start
for i in 2...length {
if (length % i == 0) {
return "NO"
}
}
return "YES"
}
```
// Fatal error: Range requires lowerBound <= upperBound
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)
let length = end - start
if length < 2 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if (start1 >= end2) || (start2 >= end1) {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length < 2 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (minStart, maxEnd) = (max(start1, start2), min(end1, end2))
let (minEnd, maxStart) = (min(end1, end2), max(start1, start2))
if minEnd > maxStart {
return "NO"
}
let length = maxEnd - minStart
return length > 1 && isPrime(num: length) ? "YES" : "NO"
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % 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 (minStart, maxEnd) = (max(start1, start2), min(end1, end2))
let (minEnd, maxStart) = (min(end1, end2), max(start1, start2))
if minEnd > maxStart {
return "NO"
}
let length = maxEnd - minStart
return length > 1 && isPrime(num: length) ? "YES" : "NO"
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (start, end) = (max(start1, start2), min(end1, end2))
if start > end {
return "NO"
}
let length = end - start
guard length > 1 else {
return "NO"
}
var isPrime = true
for i in 2..<length {
if length % i == 0 {
isPrime = false
break
}
}
return isPrime ? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (start, end) = (max(start1, start2), min(end1, end2))
if start > end {
return "NO"
}
let length = end - start
guard length > 1 else {
return "NO"
}
var isPrime = true
for i in 2..<length {
if length % i == 0 {
isPrime = false
break
}
}
return isPrime ? "YES" : "NO"
}
```
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (start, end) = (max(start1, start2), min(end1, end2))
if start > end {
return "NO"
}
let length = end - start + 1
if isPrime(number: length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(number: Int) -> Bool {
guard number > 1 else {
return false
}
var isPrime = true
for i in 2..<number {
if number % i == 0 {
isPrime = false
break
}
}
return isPrime
}
```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, end) = (max(start1, start2), min(end1, end2))
if start > end {
return "NO"
}
let length = end - start + 1
if isPrime(number: length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(number: Int) -> Bool {
guard number > 1 else {
return false
}
var isPrime = true
for i in 2..<number {
if number % i == 0 {
isPrime = false
break
}
}
return isPrime
}
```
// XCTAssertTrue failed
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if length == 1 {
return "NO"
}
if length == 2 {
return "NO"
}
if length == 3 {
return "NO"
}
if length == 5 {
return "NO"
}
if length == 7 {
return "NO"
}
if length == 11 {
return "NO"
}
if length == 13 {
return "NO"
}
if length == 17 {
return "NO"
}
if length == 19 {
return "NO"
}
if length == 23 {
return "NO"
}
if length == 29 {
return "NO"
}
if length == 31 {
return "NO"
}
if length == 37 {
return "NO"
}
if length == 41 {
return "NO"
}
if length == 43 {
return "NO"
}
if length == 47 {
return "NO"
}
if length == 53 {
return "NO"
}
if length == 59 {
return "NO"
}
if length == 61 {
return "NO"
}
if length == 67 {
return "NO"
}
if length == 71 {
return "NO"
}
if length == 73 {
return "NO"
}
if length == 79 {
return "NO"
}
if length == 83 {
return "NO"
}
if length == 89 {
return "NO"
}
if length == 97 {
return "NO"
}
if length == 101 {
return "NO"
}
if length == 103 {
return "NO"
}
if length == 107 {
return "NO"
}
if length == 109 {
return "NO"
}
if length == 113 {
return "NO"
}
if length == 127 {
return "NO"
}
if length == 131 {
return "NO"
}
if length == 137 {
return "NO"
}
if length == 139 {
return "NO"
}
if length == 149 {
return "NO"
}
if length == 151 {
return "NO"
}
if length == 157 {
return "NO"
}
if length == 163 {
return "NO"
}
if length == 167 {
return "NO"
}
if length == 173 {
return "NO"
}
if length == 179 {
return "NO"
}
if length == 181 {
return "NO"
}
if length == 191 {
return "NO"
}
if length == 193 {
return "NO"
}
if length == 197 {
return "NO"
}
if length == 199 {
return "NO"
}
if length == 211 {
return "NO"
}
if length == 223 {
return "NO"
}
if length == 227 {
return "NO"
}
if length == 229 {
return "NO"
}
if length == 2
XCTAssertTrue(intersection(interval1: (1, 2), interval2: (2, 3)) == "NO") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (-2, 2), interval2: (-4, 0)) == "YES") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (-11, 2), interval2: (-1, -1)) == "NO") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (1, 2), interval2: (3, 5)) == "NO") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (1, 2), interval2: (1, 2)) == "NO") // cannot find 'intersection' in scope
XCTAssertTrue(intersection(interval1: (-2, -2), interval2: (-3, -2)) == "NO") // cannot find 'intersection' in scope
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)
let length = end - start + 1
if (length > 1) && (2...length).allSatisfy({ length % $0 != 0}) {
return "YES"
}
return "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if (start1 >= end2) || (start2 >= end1) {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if (length > 1) && (2...length).allSatisfy({ length % $0 != 0}) {
return "YES"
}
return "NO"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (start, end) = (max(start1, start2), min(end1, end2))
if start > end {
return "NO"
}
let length = end - start + 1
if length == 1 || length == 2 {
return "NO"
}
var isPrime = true
for i in 2..<length {
if length % i == 0 {
isPrime = false
break
}
}
return isPrime ? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let (start, end) = (max(start1, start2), min(end1, end2))
if start > end {
return "NO"
}
let length = end - start + 1
if length == 1 || length == 2 {
return "NO"
}
var isPrime = true
for i in 2..<length {
if length % i == 0 {
isPrime = false
break
}
}
return isPrime ? "YES" : "NO"
}
```
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num < 0 {
product *= -1
}
sum += abs(num)
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num < 0 {
product *= -1
}
sum += abs(num)
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num > 0 {
product *= 1
} else if num < 0 {
product *= -1
} else {
product *= 0
}
sum += abs(num)
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num > 0 {
product *= 1
} else if num < 0 {
product *= -1
} else {
product *= 0
}
sum += abs(num)
}
return sum * product
}
```
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else {
return nil
}
let sum = arr.reduce(0, +)
let product = arr.reduce(1, *)
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else {
return nil
}
let sum = arr.reduce(0, +)
let product = arr.reduce(1, *)
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num != 0 {
product *= num > 0 ? 1 : -1
}
sum += abs(num)
}
return product * 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 sum = 0
var product = 1
for num in arr {
if num != 0 {
product *= num > 0 ? 1 : -1
}
sum += abs(num)
}
return product * sum
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else {
return nil
}
var sum = 0
var product = 1
for number in arr {
if number != 0 {
product *= number > 0 ? 1 : -1
sum += abs(number)
}
}
return product * 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 sum = 0
var product = 1
for number in arr {
if number != 0 {
product *= number > 0 ? 1 : -1
sum += abs(number)
}
}
return product * sum
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else {
return nil
}
var sum = 0
var product = 1
for i in 0..<arr.count {
if arr[i] != 0 {
sum += arr[i]
product *= arr[i] > 0 ? 1 : -1
}
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else {
return nil
}
var sum = 0
var product = 1
for i in 0..<arr.count {
if arr[i] != 0 {
sum += arr[i]
product *= arr[i] > 0 ? 1 : -1
}
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
sum += abs(num)
product *= num == 0 ? 1 : num > 0 ? 1 : -1
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count != 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
sum += abs(num)
product *= num == 0 ? 1 : num > 0 ? 1 : -1
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else {
return nil
}
var sum = 0
var product = 1
for i in arr {
sum += i
product *= i == 0 ? 1 : i > 0 ? 1 : -1
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else {
return nil
}
var sum = 0
var product = 1
for i in arr {
sum += i
product *= i == 0 ? 1 : i > 0 ? 1 : -1
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num > 0 {
sum += num
product *= 1
} else if num < 0 {
sum -= num
product *= -1
} else {
product *= 0
}
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num > 0 {
sum += num
product *= 1
} else if num < 0 {
sum -= num
product *= -1
} else {
product *= 0
}
}
return sum * product
}
```
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num == 0 {
sum += 0
} else if num < 0 {
sum -= num
product *= -1
} else {
sum += num
}
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var sum = 0
var product = 1
for num in arr {
if num == 0 {
sum += 0
} else if num < 0 {
sum -= num
product *= -1
} else {
sum += num
}
}
return sum * product
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
}
```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] {
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
// TODO
}
```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] {
// TODO
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
// Write your code here
return []
}
```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
return []
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
var grid = grid
var result = [Int]()
var visited = Array(repeating: Array(repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int)]()
for i in 0..<grid.count {
for j in 0..<grid[0].count {
if grid[i][j] == 1 {
queue.append((i, j))
visited[i][j] = true
break
}
}
}
while !queue.isEmpty {
let (i, j) = queue.removeFirst()
result.append(grid[i][j])
if result.count == k {
return result
}
if i > 0 && !visited[i-1][j] {
queue.append((i-1, j))
visited[i-1][j] = true
}
if i < grid.count-1 && !visited[i+1][j] {
queue.append((i+1, j))
visited[i+1][j] = true
}
if j > 0 && !visited[i][j-1] {
queue.append((i, j-1))
visited[i][j-1] = true
}
if j < grid[0].count-1 && !visited[i][j+1] {
queue.append((i, j+1))
visited[i][j+1] = true
}
}
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 grid = grid
var result = [Int]()
var visited = Array(repeating: Array(repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int)]()
for i in 0..<grid.count {
for j in 0..<grid[0].count {
if grid[i][j] == 1 {
queue.append((i, j))
visited[i][j] = true
break
}
}
}
while !queue.isEmpty {
let (i, j) = queue.removeFirst()
result.append(grid[i][j])
if result.count == k {
return result
}
if i > 0 && !visited[i-1][j] {
queue.append((i-1, j))
visited[i-1][j] = true
}
if i < grid.count-1 && !visited[i+1][j] {
queue.append((i+1, j))
visited[i+1][j] = true
}
if j > 0 && !visited[i][j-1] {
queue.append((i, j-1))
visited[i][j-1] = true
}
if j < grid[0].count-1 && !visited[i][j+1] {
queue.append((i, j+1))
visited[i][j+1] = true
}
}
return result
}
```
var grid = grid // variable 'grid' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let k = k - 1
var dp = [[Int]](repeating: [Int](repeating: Int.max, count: m), count: n)
for i in 0..<n {
for j in 0..<m {
dp[i][j] = grid[i][j]
}
}
for i in 0..<n {
for j in 0..<m {
if i - 1 >= 0 {
dp[i][j] = min(dp[i][j], dp[i - 1][j] + grid[i][j])
}
if j - 1 >= 0 {
dp[i][j] = min(dp[i][j], dp[i][j - 1] + grid[i][j])
}
if i + 1 < n {
dp[i][j] = min(dp[i][j], dp[i + 1][j] + grid[i][j])
}
if j + 1 < m {
dp[i][j] = min(dp[i][j], dp[i][j + 1] + grid[i][j])
}
}
}
var res = [Int]()
var i = n - 1
var j = m - 1
for _ in 0..<k {
res.append(grid[i][j])
if i - 1 >= 0 && dp[i - 1][j] < dp[i][j] {
i -= 1
} else if j - 1 >= 0 && dp[i][j - 1] < dp[i][j] {
j -= 1
} else if i + 1 < n && dp[i + 1][j] < dp[i][j] {
i += 1
} else if j + 1 < m && dp[i][j + 1] < dp[i][j] {
j += 1
}
}
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
let m = grid[0].count
let k = k - 1
var dp = [[Int]](repeating: [Int](repeating: Int.max, count: m), count: n)
for i in 0..<n {
for j in 0..<m {
dp[i][j] = grid[i][j]
}
}
for i in 0..<n {
for j in 0..<m {
if i - 1 >= 0 {
dp[i][j] = min(dp[i][j], dp[i - 1][j] + grid[i][j])
}
if j - 1 >= 0 {
dp[i][j] = min(dp[i][j], dp[i][j - 1] + grid[i][j])
}
if i + 1 < n {
dp[i][j] = min(dp[i][j], dp[i + 1][j] + grid[i][j])
}
if j + 1 < m {
dp[i][j] = min(dp[i][j], dp[i][j + 1] + grid[i][j])
}
}
}
var res = [Int]()
var i = n - 1
var j = m - 1
for _ in 0..<k {
res.append(grid[i][j])
if i - 1 >= 0 && dp[i - 1][j] < dp[i][j] {
i -= 1
} else if j - 1 >= 0 && dp[i][j - 1] < dp[i][j] {
j -= 1
} else if i + 1 < n && dp[i + 1][j] < dp[i][j] {
i += 1
} else if j + 1 < m && dp[i][j + 1] < dp[i][j] {
j += 1
}
}
res.append(grid[i][j])
return res
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
var grid = grid
let n = grid.count
let m = grid[0].count
for i in 0..<k {
var minVal = Int.max
var minRow = 0
var minCol = 0
for row in 0..<n {
for col in 0..<m {
if grid[row][col] < minVal {
minVal = grid[row][col]
minRow = row
minCol = col
}
}
}
grid[minRow][minCol] = Int.max
}
return Array(grid[minRow][minCol])
}
```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 grid = grid
let n = grid.count
let m = grid[0].count
for i in 0..<k {
var minVal = Int.max
var minRow = 0
var minCol = 0
for row in 0..<n {
for col in 0..<m {
if grid[row][col] < minVal {
minVal = grid[row][col]
minRow = row
minCol = col
}
}
}
grid[minRow][minCol] = Int.max
}
return Array(grid[minRow][minCol])
}
```
return Array(grid[minRow][minCol]) // cannot find 'minCol' in scope
return Array(grid[minRow][minCol]) // cannot find 'minRow' in scope
func minPath(grid: [[Int]], k: Int) -> [Int] {
var grid = grid
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Int.max, count: m), count: n)
var ans = Array(repeating: 0, count: k)
var queue = PriorityQueue<Int, Int>(sort: <)
for i in 0 ..< n {
for j in 0 ..< m {
if grid[i][j] == 1 {
dp[i][j] = 0
queue.insert(i * m + j, priority: 0)
}
}
}
while !queue.isEmpty() {
let (i, j) = (queue.peek() / m, queue.peek() % m)
queue.remove()
if dp[i][j] == k {
ans = Array(grid[i][j ...])
break
}
for (x, y) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)] {
if x >= 0 && x < n && y >= 0 && y < m && dp[x][y] > dp[i][j] + 1 {
dp[x][y] = dp[i][j] + 1
queue.insert(x * m + y, priority: dp[x][y])
}
}
}
return ans
}
```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 grid = grid
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Int.max, count: m), count: n)
var ans = Array(repeating: 0, count: k)
var queue = PriorityQueue<Int, Int>(sort: <)
for i in 0 ..< n {
for j in 0 ..< m {
if grid[i][j] == 1 {
dp[i][j] = 0
queue.insert(i * m + j, priority: 0)
}
}
}
while !queue.isEmpty() {
let (i, j) = (queue.peek() / m, queue.peek() % m)
queue.remove()
if dp[i][j] == k {
ans = Array(grid[i][j ...])
break
}
for (x, y) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)] {
if x >= 0 && x < n && y >= 0 && y < m && dp[x][y] > dp[i][j] + 1 {
dp[x][y] = dp[i][j] + 1
queue.insert(x * m + y, priority: dp[x][y])
}
}
}
return ans
}
```
var queue = PriorityQueue<Int, Int>(sort: <) // cannot find 'PriorityQueue' in scope
ans = Array(grid[i][j ...]) // missing argument for parameter #1 in subscript
ans = Array(grid[i][j ...]) // expected expression after operator
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
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]()
return result
}
```
var result = [Int]() // variable 'result' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
var grid = grid
var result = [Int]()
var currentRow = 0
var currentColumn = 0
for _ in 0 ..< k {
result.append(grid[currentRow][currentColumn])
if currentRow == grid.count - 1 {
currentColumn += 1
} else if currentColumn == grid[currentRow].count - 1 {
currentRow += 1
} else if grid[currentRow + 1][currentColumn] < grid[currentRow][currentColumn + 1] {
currentRow += 1
} else {
currentColumn += 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 grid = grid
var result = [Int]()
var currentRow = 0
var currentColumn = 0
for _ in 0 ..< k {
result.append(grid[currentRow][currentColumn])
if currentRow == grid.count - 1 {
currentColumn += 1
} else if currentColumn == grid[currentRow].count - 1 {
currentRow += 1
} else if grid[currentRow + 1][currentColumn] < grid[currentRow][currentColumn + 1] {
currentRow += 1
} else {
currentColumn += 1
}
}
return result
}
```
var grid = grid // variable 'grid' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let k = k
let grid = grid
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<k {
for j in 0..<n {
for l in 0..<m {
dp[i][j][l] = Int.max
}
}
}
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1..<k {
for j in 0..<n {
for l in 0..<m {
for p in 0..<n {
for q in 0..<m {
if p == j && q == l {
continue
}
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][p][q])
}
}
dp[i][j][l] += grid[j][l]
}
}
}
var ans = [Int]()
var min_val = Int.max
var min_i = -1
var min_j = -1
for i in 0..<n {
for j in 0..<m {
if dp[k - 1][i][j] < min_val {
min_val = dp[k - 1][i][j]
min_i = i
min_j = j
}
}
}
ans.append(grid[min_i][min_j])
for i in 1..<k {
var min_val = Int.max
var min_i = -1
var min_j = -1
for j in 0..<n {
for l in 0..<m {
if dp[i - 1][j][l] == dp[i - 1][min_i][min_j] {
if grid[j][l] < grid[min_i][min_j] {
min_i = j
min_j = l
}
} else if dp[i - 1][j][l] < dp[i - 1][min_i][min_j] {
min_i = j
min_j = l
}
}
}
ans.append(grid[min_i][min_j])
}
return ans
}
```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
let m = grid[0].count
let k = k
let grid = grid
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<k {
for j in 0..<n {
for l in 0..<m {
dp[i][j][l] = Int.max
}
}
}
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1..<k {
for j in 0..<n {
for l in 0..<m {
for p in 0..<n {
for q in 0..<m {
if p == j && q == l {
continue
}
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][p][q])
}
}
dp[i][j][l] += grid[j][l]
}
}
}
var ans = [Int]()
var min_val = Int.max
var min_i = -1
var min_j = -1
for i in 0..<n {
for j in 0..<m {
if dp[k - 1][i][j] < min_val {
min_val = dp[k - 1][i][j]
min_i = i
min_j = j
}
}
}
ans.append(grid[min_i][min_j])
for i in 1..<k {
var min_val = Int.max
var min_i = -1
var min_j = -1
for j in 0..<n {
for l in 0..<m {
if dp[i - 1][j][l] == dp[i - 1][min_i][min_j] {
if grid[j][l] < grid[min_i][min_j] {
min_i = j
min_j = l
}
} else if dp[i - 1][j][l] < dp[i - 1][min_i][min_j] {
min_i = j
min_j = l
}
}
}
ans.append(grid[min_i][min_j])
}
return ans
}
```
var min_val = Int.max // initialization of variable 'min_val' was never used; consider replacing with assignment to '_' or removing it
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [Int]()
var n = n
while n >= 0 {
if n == 0 {
result.append(1)
} else if n == 1 {
result.append(3)
} else if n == 2 {
result.append(2)
} else {
let last = result.last!
let secondLast = result[result.count - 2]
let thirdLast = result[result.count - 3]
if n % 2 == 0 {
result.append(1 + n / 2)
} else {
result.append(last + secondLast + thirdLast)
}
}
n -= 1
}
return result.reversed()
}
```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]()
var n = n
while n >= 0 {
if n == 0 {
result.append(1)
} else if n == 1 {
result.append(3)
} else if n == 2 {
result.append(2)
} else {
let last = result.last!
let secondLast = result[result.count - 2]
let thirdLast = result[result.count - 3]
if n % 2 == 0 {
result.append(1 + n / 2)
} else {
result.append(last + secondLast + thirdLast)
}
}
n -= 1
}
return result.reversed()
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func tri(n: Int) -> [Int] {
var result = [Int]()
var n1 = 1
var n2 = 3
var n3 = 2
for _ in 1...n {
result.append(n1)
result.append(n2)
result.append(n3)
n1 = n2
n2 = n3
n3 = n1 + n2 + n3
}
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]()
var n1 = 1
var n2 = 3
var n3 = 2
for _ in 1...n {
result.append(n1)
result.append(n2)
result.append(n3)
n1 = n2
n2 = n3
n3 = n1 + n2 + n3
}
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3, 2]
if n <= 2 {
return result.prefix(n+1).map { $0 }
}
for i in 3...n {
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 result.prefix(n+1).map { $0 }
}
for i in 3...n {
result.append(result[i-1] + result[i-2] + result[i+1])
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [Int]()
var n = n
while n >= 0 {
if n % 2 == 0 {
result.append(1 + n / 2)
} else {
let n1 = result[n - 1]
let n2 = result[n - 2]
let n3 = result[n + 1]
result.append(n1 + n2 + n3)
}
n -= 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]()
var n = n
while n >= 0 {
if n % 2 == 0 {
result.append(1 + n / 2)
} else {
let n1 = result[n - 1]
let n2 = result[n - 2]
let n3 = result[n + 1]
result.append(n1 + n2 + n3)
}
n -= 1
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [Int]()
var a = 1
var b = 3
var c = 2
for _ in 0 ..< n + 1 {
result.append(a)
if n % 2 == 0 {
a = 1 + n / 2
} else {
let temp = a
a = b
b = c
c = temp + b + 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]()
var a = 1
var b = 3
var c = 2
for _ in 0 ..< n + 1 {
result.append(a)
if n % 2 == 0 {
a = 1 + n / 2
} else {
let temp = a
a = b
b = c
c = temp + b + c
}
}
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n + 1 {
if i == 1 {
result.append(3)
} else if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 2] + result[i - 1] + 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]()
for i in 1...n + 1 {
if i == 1 {
result.append(3)
} else if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 2] + result[i - 1] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
if i == 0 {
result.append(1)
} else if i == 1 {
result.append(3)
} else if i == 2 {
result.append(2)
} else if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
if i == 0 {
result.append(1)
} else if i == 1 {
result.append(3)
} else if i == 2 {
result.append(2)
} else if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func digits(n: Int) -> Int {
let digits = String(n).characters.map { Int(String($0))! }
return digits.reduce(1, combine: { $0 * ($1 % 2 != 0 ? $1 : 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 {
let digits = String(n).characters.map { Int(String($0))! }
return digits.reduce(1, combine: { $0 * ($1 % 2 != 0 ? $1 : 1) })
}
```
let digits = String(n).characters.map { Int(String($0))! } // 'characters' is unavailable: Please use String directly
return digits.reduce(1, combine: { $0 * ($1 % 2 != 0 ? $1 : 1) }) // extraneous argument label 'combine:' in call
func digits(n: Int) -> Int {
var product = 1
var n = n
while n > 0 {
let digit = n % 10
if digit % 2 != 0 {
product *= digit
}
n /= 10
}
return product
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var product = 1
var n = n
while n > 0 {
let digit = n % 10
if digit % 2 != 0 {
product *= digit
}
n /= 10
}
return product
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var num = n
var product = 1
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
product *= digit
}
num /= 10
}
return product
}
```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 num = n
var product = 1
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
product *= digit
}
num /= 10
}
return product
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var num = n
var product = 1
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
product *= digit
}
num /= 10
}
return product
}
```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 num = n
var product = 1
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
product *= digit
}
num /= 10
}
return product
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
let digits = String(n).map { Int(String($0))! }
return digits.filter { $0 % 2 != 0 }.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 {
let digits = String(n).map { Int(String($0))! }
return digits.filter { $0 % 2 != 0 }.reduce(1, *)
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var n = n
while n > 0 {
let digit = n % 10
if digit % 2 == 1 {
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 = 1
var n = n
while n > 0 {
let digit = n % 10
if digit % 2 == 1 {
result *= digit
}
n /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
let digits = String(n).compactMap { Int(String($0)) }
let oddDigits = digits.filter { $0 % 2 == 1 }
return oddDigits.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 {
let digits = String(n).compactMap { Int(String($0)) }
let oddDigits = digits.filter { $0 % 2 == 1 }
return oddDigits.reduce(1, *)
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
let digits = String(n).map { Int(String($0))! }
return digits.reduce(1) { $0 * ($1 % 2 != 0 ? $1 : 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 {
let digits = String(n).map { Int(String($0))! }
return digits.reduce(1) { $0 * ($1 % 2 != 0 ? $1 : 1) }
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var n = n
var result = 1
while n > 0 {
let digit = n % 10
if digit % 2 != 0 {
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 n = n
var result = 1
while n > 0 {
let digit = n % 10
if digit % 2 != 0 {
result *= digit
}
n /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
let digits = String(n).map{Int(String($0))!}
let oddDigits = digits.filter{$0%2 == 1}
if oddDigits.isEmpty { return 0 }
return oddDigits.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 {
let digits = String(n).map{Int(String($0))!}
let oddDigits = digits.filter{$0%2 == 1}
if oddDigits.isEmpty { return 0 }
return oddDigits.reduce(1, *)
}
```
func isNested(string: String) -> Bool {
var stack = [Character]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
count += 1
if count >= 2 {
if stack.count > 0 {
return true
}
}
}
return stack.count == 0
}
```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]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
count += 1
if count >= 2 {
if stack.count > 0 {
return true
}
}
}
return stack.count == 0
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let brackets = string.filter { $0 == "[" || $0 == "]" }
if brackets.count % 2 != 0 {
return false
}
var stack = [Character]()
for char in brackets {
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 {
let brackets = string.filter { $0 == "[" || $0 == "]" }
if brackets.count % 2 != 0 {
return false
}
var stack = [Character]()
for char in brackets {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let arr = Array(string)
var count = 0
for i in arr {
if i == "[" {
count += 1
} else {
count -= 1
}
if count < 0 {
return false
}
}
return count == 0
}
```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 {
let arr = Array(string)
var count = 0
for i in arr {
if i == "[" {
count += 1
} else {
count -= 1
}
if count < 0 {
return false
}
}
return count == 0
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let stack = Stack<Character>()
for char in string {
if char == "[" {
stack.push(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
let stack = Stack<Character>()
for char in string {
if char == "[" {
stack.push(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```
let stack = Stack<Character>() // cannot find 'Stack' in scope
func isNested(string: String) -> Bool {
var stack = [Character]()
var isNested = false
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
isNested = false
break
} else {
stack.popLast()
isNested = true
}
}
}
return isNested
}
```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]()
var isNested = false
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
isNested = false
break
} else {
stack.popLast()
isNested = true
}
}
}
return isNested
}
```
stack.popLast() // result of call to 'popLast()' is unused
// 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.popLast()
}
}
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.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let arr = Array(string)
var count = 0
var count2 = 0
for i in arr {
if i == "[" {
count += 1
} else if i == "]" {
count2 += 1
}
if count2 > count {
return false
}
}
return count2 == count
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
let arr = Array(string)
var count = 0
var count2 = 0
for i in arr {
if i == "[" {
count += 1
} else if i == "]" {
count2 += 1
}
if count2 > count {
return false
}
}
return count2 == count
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let arr = Array(string)
var stack = [Character]()
for char in arr {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.popLast()
}
}
}
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 {
let arr = Array(string)
var stack = [Character]()
for char in arr {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
} else {
stack.popLast()
}
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
// 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]()
var isNested = false
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.count > 1 {
stack.popLast()
isNested = true
} else {
return false
}
}
}
return isNested
}
```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]()
var isNested = false
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.count > 1 {
stack.popLast()
isNested = true
} else {
return false
}
}
}
return isNested
}
```
stack.popLast() // result of call to 'popLast()' is unused
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int($0.rounded(.up)) * Int($0.rounded(.up)) }.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($0.rounded(.up)) * Int($0.rounded(.up)) }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int($0.rounded()) }
.map { $0 * $0 }
.reduce(0, +)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int($0.rounded()) }
.map { $0 * $0 }
.reduce(0, +)
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) * 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 { ceil($0) * ceil($0) }.reduce(0, +)
}
```
return lst.map { ceil($0) * ceil($0) }.reduce(0, +) // cannot convert value of type 'Double' to closure result type 'Int'
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int($0.rounded(.up)) }.reduce(0) { $0 + $1 * $1 }
}
```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($0.rounded(.up)) }.reduce(0) { $0 + $1 * $1 }
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int($0.rounded()) }
.map { $0 * $0 }
.reduce(0, +)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int($0.rounded()) }
.map { $0 * $0 }
.reduce(0, +)
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) * 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 { ceil($0) * ceil($0) }.reduce(0, +)
}
```
return lst.map { ceil($0) * ceil($0) }.reduce(0, +) // cannot convert value of type 'Double' to closure result type 'Int'
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) * 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 { ceil($0) * ceil($0) }.reduce(0, +)
}
```
return lst.map { ceil($0) * ceil($0) }.reduce(0, +) // cannot convert value of type 'Double' to closure result type 'Int'
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) }.reduce(0) { $0 + $1 * $1 }
}
```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 { ceil($0) }.reduce(0) { $0 + $1 * $1 }
}
```
return lst.map { ceil($0) }.reduce(0) { $0 + $1 * $1 } // cannot convert return expression of type 'Double' to return type 'Int'
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) }.reduce(0) { $0 + $1 * $1 }
}
```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 { ceil($0) }.reduce(0) { $0 + $1 * $1 }
}
```
return lst.map { ceil($0) }.reduce(0) { $0 + $1 * $1 } // cannot convert return expression of type 'Double' to return type 'Int'
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) }.map { $0 * $0 }.reduce(0, +)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { ceil($0) }.map { $0 * $0 }.reduce(0, +)
}
```
return lst.map { ceil($0) }.map { $0 * $0 }.reduce(0, +) // cannot convert value of type 'Double' to closure result type 'Int'
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last!
if lastChar.isLetter && !txt.contains(" ") {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last!
if lastChar.isLetter && !txt.contains(" ") {
return true
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.last == " " {
return false
}
if txt.last == nil {
return false
}
if txt.last == "e" {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.last == " " {
return false
}
if txt.last == nil {
return false
}
if txt.last == "e" {
return true
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastCharacter = txt.last!
let lastCharacterIsALetter = lastCharacter.isLetter
let lastCharacterIsNotInAWord = txt.last != " "
return lastCharacterIsALetter && lastCharacterIsNotInAWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastCharacter = txt.last!
let lastCharacterIsALetter = lastCharacter.isLetter
let lastCharacterIsNotInAWord = txt.last != " "
return lastCharacterIsALetter && lastCharacterIsNotInAWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last
let lastCharIsALetter = lastChar?.isLetter ?? false
let lastCharIsLastInWord = txt.contains(" ") && txt.last != " "
return lastCharIsALetter && lastCharIsLastInWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last
let lastCharIsALetter = lastChar?.isLetter ?? false
let lastCharIsLastInWord = txt.contains(" ") && txt.last != " "
return lastCharIsALetter && lastCharIsLastInWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastCharacter = txt.last!
if lastCharacter == " " {
return false
}
return lastCharacter.isLetter
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastCharacter = txt.last!
if lastCharacter == " " {
return false
}
return lastCharacter.isLetter
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
return lastChar?.isLetter == true && lastChar != " "
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
return lastChar?.isLetter == true && lastChar != " "
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if let lastChar = lastChar, lastChar.isLetter {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if let lastChar = lastChar, lastChar.isLetter {
return true
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if lastChar?.isLetter ?? false {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if lastChar?.isLetter ?? false {
return true
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if let lastChar = lastChar,
lastChar != " " {
return CharacterSet.letters.contains(UnicodeScalar(lastChar.lowercased())!)
}
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 {
let lastChar = txt.last
if let lastChar = lastChar,
lastChar != " " {
return CharacterSet.letters.contains(UnicodeScalar(lastChar.lowercased())!)
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = lastChar?.isLetter
let isWord = txt.hasSuffix(" ")
return isLetter ?? false && !isWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = lastChar?.isLetter
let isWord = txt.hasSuffix(" ")
return isLetter ?? false && !isWord
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
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 {
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
for i in 1..<arr.count {
if arr[i - 1] > arr[i] {
return i - 1
}
}
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 {
for i in 1..<arr.count {
if arr[i - 1] > arr[i] {
return i - 1
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
guard arr.count > 1 else {
return -1
}
var result = -1
for index in 0..<arr.count-1 {
if arr[index] < arr[index+1] {
result = index
}
}
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 {
guard arr.count > 1 else {
return -1
}
var result = -1
for index in 0..<arr.count-1 {
if arr[index] < arr[index+1] {
result = index
}
}
return result
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var largestIndex = -1
for i in 1..<arr.count {
if arr[i - 1] > arr[i] {
largestIndex = i - 1
}
}
return largestIndex
}
```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 largestIndex = -1
for i in 1..<arr.count {
if arr[i - 1] > arr[i] {
largestIndex = i - 1
}
}
return largestIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
// Write your code here
var index = -1
for i in 1..<arr.count {
if arr[i] <= arr[i-1] {
index = i
}
}
return index
}
```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
var index = -1
for i in 1..<arr.count {
if arr[i] <= arr[i-1] {
index = i
}
}
return index
}
```
// Fatal error: Range requires lowerBound <= upperBound
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 1..<arr.count {
if arr[i] <= arr[i - 1] {
maxIndex = i - 1
}
}
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 1..<arr.count {
if arr[i] <= arr[i - 1] {
maxIndex = i - 1
}
}
return maxIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
for i in 1..<arr.count {
if arr[i - 1] < arr[i] {
return i - 1
}
}
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 {
for i in 1..<arr.count {
if arr[i - 1] < arr[i] {
return i - 1
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
for i in 0..<arr.count - 1 {
if arr[i] > arr[i + 1] {
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 {
for i in 0..<arr.count - 1 {
if arr[i] > arr[i + 1] {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
guard arr.count > 1 else { return -1 }
let sorted = arr.sorted()
for i in 0 ..< sorted.count - 1 {
if sorted[i] < sorted[i + 1] {
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 {
guard arr.count > 1 else { return -1 }
let sorted = arr.sorted()
for i in 0 ..< sorted.count - 1 {
if sorted[i] < sorted[i + 1] {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
if arr.isEmpty { return -1 }
var result = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i+1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
if arr.isEmpty { return -1 }
var result = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i+1] {
result = i
}
}
return result
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for number in lst {
if number > 0 {
if let smallest = smallest {
if number < smallest {
smallest = number
}
} else {
smallest = number
}
} else if number < 0 {
if let largest = largest {
if number > largest {
largest = number
}
} else {
largest = number
}
}
}
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?
var smallest: Int?
for number in lst {
if number > 0 {
if let smallest = smallest {
if number < smallest {
smallest = number
}
} else {
smallest = number
}
} else if number < 0 {
if let largest = largest {
if number > largest {
largest = number
}
} else {
largest = number
}
}
}
return (largest, smallest)
}
```
smallest = number // cannot assign to value: 'smallest' is a 'let' constant
largest = number // cannot assign to value: 'largest' is a 'let' constant
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largestNegative: Int? = nil
var smallestPositive: Int? = nil
for number in lst {
if number < 0 {
if largestNegative == nil || number > largestNegative! {
largestNegative = number
}
} else if number > 0 {
if smallestPositive == nil || number < smallestPositive! {
smallestPositive = number
}
}
}
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 number in lst {
if number < 0 {
if largestNegative == nil || number > largestNegative! {
largestNegative = number
}
} else if number > 0 {
if smallestPositive == nil || number < smallestPositive! {
smallestPositive = number
}
}
}
return (largestNegative, smallestPositive)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
return (negative.max(), positive.min())
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
return (negative.max(), positive.min())
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
if negative.isEmpty || positive.isEmpty {
return (nil, nil)
}
return (negative.max(), positive.min())
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
if negative.isEmpty || positive.isEmpty {
return (nil, nil)
}
return (negative.max(), positive.min())
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for i in lst {
if i < 0 {
if largest == nil || i > largest! {
largest = i
}
} else if i > 0 {
if smallest == nil || i < smallest! {
smallest = i
}
}
}
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 i in lst {
if i < 0 {
if largest == nil || i > largest! {
largest = i
}
} else if i > 0 {
if smallest == nil || i < smallest! {
smallest = i
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var smallestPositive = Int.max
var largestNegative = Int.min
var hasPositive = false
var hasNegative = false
for i in lst {
if i > 0 {
hasPositive = true
if i < smallestPositive {
smallestPositive = i
}
}
if i < 0 {
hasNegative = true
if i > largestNegative {
largestNegative = i
}
}
}
if hasPositive && hasNegative {
return (largestNegative, smallestPositive)
} 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 smallestPositive = Int.max
var largestNegative = Int.min
var hasPositive = false
var hasNegative = false
for i in lst {
if i > 0 {
hasPositive = true
if i < smallestPositive {
smallestPositive = i
}
}
if i < 0 {
hasNegative = true
if i > largestNegative {
largestNegative = i
}
}
}
if hasPositive && hasNegative {
return (largestNegative, smallestPositive)
} else {
return (nil, nil)
}
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negatives = lst.filter { $0 < 0 }
var positives = lst.filter { $0 > 0 }
if negatives.count == 0 || positives.count == 0 {
return (nil, nil)
} else {
return (negatives.max(), positives.min())
}
}
```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 = lst.filter { $0 < 0 }
var positives = lst.filter { $0 > 0 }
if negatives.count == 0 || positives.count == 0 {
return (nil, nil)
} else {
return (negatives.max(), positives.min())
}
}
```
var negatives = lst.filter { $0 < 0 } // variable 'negatives' was never mutated; consider changing to 'let' constant
var positives = lst.filter { $0 > 0 } // variable 'positives' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largestNegative: Int?
var smallestPositive: Int?
for num in lst {
if num < 0 {
if let currentLargestNegative = largestNegative {
largestNegative = max(currentLargestNegative, num)
} else {
largestNegative = num
}
} else if num > 0 {
if let currentSmallestPositive = smallestPositive {
smallestPositive = min(currentSmallestPositive, num)
} else {
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?
var smallestPositive: Int?
for num in lst {
if num < 0 {
if let currentLargestNegative = largestNegative {
largestNegative = max(currentLargestNegative, num)
} else {
largestNegative = num
}
} else if num > 0 {
if let currentSmallestPositive = smallestPositive {
smallestPositive = min(currentSmallestPositive, num)
} else {
smallestPositive = num
}
}
}
return (largestNegative, smallestPositive)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var smallest = Int.max
var largest = Int.min
for i in lst {
if i < smallest && i > 0 {
smallest = i
}
if i > largest && i < 0 {
largest = i
}
}
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 smallest = Int.max
var largest = Int.min
for i in lst {
if i < smallest && i > 0 {
smallest = i
}
if i > largest && i < 0 {
largest = i
}
}
return (largest, smallest)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var positive = Int.max
var negative = Int.min
for num in lst {
if num > 0 {
positive = min(positive, num)
} else if num < 0 {
negative = max(negative, num)
}
}
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 positive = Int.max
var negative = Int.min
for num in lst {
if num > 0 {
positive = min(positive, num)
} else if num < 0 {
negative = max(negative, num)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
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 aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
guard let a = Double(aString.replacingOccurrences(of: ",", with: ".")),
let b = Double(bString.replacingOccurrences(of: ",", with: ".")) else {
return nil
}
return a > b ? a : b
default:
return nil
}
}
func compareMany(a: [Value], b: [Value]) -> [Value]? {
guard a.count == b.count else { return nil }
let zipped = zip(a, b)
let result = zipped.compactMap { compareOne(a: $0.0, b: $0.1) }
return result.count == a.count ? result : 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 aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
guard let a = Double(aString.replacingOccurrences(of: ",", with: ".")),
let b = Double(bString.replacingOccurrences(of: ",", with: ".")) else {
return nil
}
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes arrays of 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 ,
// compareMany(a: [.intValue(1), .doubleValue(2.5)], b: [.stringValue("2,3"), .intValue(3)]) == [.stringValue("2,3"), .intValue(3)]
// compareMany(a: [.intValue(1), .stringValue("2,3")], b: [.stringValue("5,1"), .stringValue("6")]) == [.stringValue("6")]
// compareMany(a: [.stringValue("1"), .intValue(1)], b: [.stringValue("1"), .intValue(1)]) == nil
func compareMany(a: [Value], b: [Value]) -> [Value]? {
guard a.count == b.count else { return nil }
let zipped = zip(a, b)
let result = zipped.compactMap { compareOne(a: $0.0, b: $0.1) }
return result.count == a.count ? result : nil
}
```
return a > b ? a : b // cannot convert return expression of type 'Double' to return type '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 ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: [Value], b: [Value]) -> [Value]? {
guard a.count == b.count else {
return nil
}
for i in 0..<a.count {
if let result = compareOne(a: a[i], b: b[i]) {
return [result]
}
}
return nil
}
func compareThree(a: [Value], b: [Value], c: [Value]) -> [Value]? {
guard a.count == b.count && b.count == c.count else {
return nil
}
for i in 0..<a.count {
if let result = compareOne(a: a[i], b: b[i]) {
if let result = compareOne(a: result, b: c[i]) {
return [result]
}
}
}
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 ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two arrays of 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: [1, 2.5], b: [2, 3]) == [2, 3]
// compareTwo(a: [1, 2.5], b: ["2,3", "3,4"]) == ["2,3", "3,4"]
// compareTwo(a: ["5,1", "6"], b: ["6", "7"]) == ["6", "7"]
// compareTwo(a: ["1", 1], b: [1, 1]) == nil
func compareTwo(a: [Value], b: [Value]) -> [Value]? {
guard a.count == b.count else {
return nil
}
for i in 0..<a.count {
if let result = compareOne(a: a[i], b: b[i]) {
return [result]
}
}
return nil
}
// Create a function that takes three arrays of 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: [1, 2.5], b: [2, 3], c: [3, 4]) == [3, 4]
// compareThree(a: [1, 2.5], b: ["2,3", "3,4"], c: [3, 4]) == ["2,3", "3,4"]
// compareThree(a: ["5,1", "6"], b: ["6", "7"], c: ["7", "8"]) == ["7", "8"]
// compareThree(a: ["1", 1], b: [1, 1], c: [1, 1]) == nil
func compareThree(a: [Value], b: [Value], c: [Value]) -> [Value]? {
guard a.count == b.count && b.count == c.count else {
return nil
}
for i in 0..<a.count {
if let result = compareOne(a: a[i], b: b[i]) {
if let result = compareOne(a: result, b: c[i]) {
return [result]
}
}
}
return nil
}
// Create a function that takes four arrays of 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: [1, 2.5], b: [2, 3], c: [3, 4], d: [4, 5]) == [4, 5]
// compareFour(a: [1, 2.5], b: ["2,3", "3,4"], c: [3, 4], d: [4, 5]) == ["2,3", "3,4"]
// compareFour(a: ["5,1", "6"], b: ["6", "7"], c: ["7", "8"], d: ["8", "9"]) == ["7", "8"]
// compareFour(a: ["1", 1], b: [1, 1], c: [1, 1], d: [1, 1]) == nil
func compareFour(a: [Value], b: [Value], c: [Value], d: [Value]) -> [Value]? {
guard a.count == b.count && b.count == c.count && c.count == d.count else {
return nil
}
for i in 0
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type '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 aInt), .intValue(let bInt)):
return aInt > bInt ? .intValue(aInt) : (bInt > aInt ? .intValue(bInt) : nil)
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : (bDouble > aDouble ? .doubleValue(bDouble) : nil)
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? .stringValue(aString) : (bString > aString ? .stringValue(bString) : nil)
default:
return nil
}
}
func compareAll(_ values: [Value]) -> Value? {
guard let first = values.first else { return nil }
return values.allSatisfy { compareOne(a: first, b: $0) == first } ? nil : first
}
```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 aInt), .intValue(let bInt)):
return aInt > bInt ? .intValue(aInt) : (bInt > aInt ? .intValue(bInt) : nil)
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : (bDouble > aDouble ? .doubleValue(bDouble) : nil)
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? .stringValue(aString) : (bString > aString ? .stringValue(bString) : nil)
default:
return nil
}
}
// Create a function that takes an array of 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 compareAll(_ values: [Value]) -> Value? {
guard let first = values.first else { return nil }
return values.allSatisfy { compareOne(a: first, b: $0) == first } ? nil : first
}
print(compareOne(a: .intValue(1), b: .intValue(2)))
print(compareOne(a: .intValue(1), b: .doubleValue(2.5)))
print(compareOne(a: .intValue(1), b: .stringValue("2,3")))
print(compareOne(a: .stringValue("5,1"), b: .stringValue("6")))
print(compareOne(a: .stringValue("1"), b: .intValue(1)))
print(compareAll([.intValue(1), .intValue(2)]))
print(compareAll([.intValue(1), .doubleValue(2.5)]))
print(compareAll([.intValue(1), .stringValue("2,3")]))
print(compareAll([.stringValue("5,1"), .stringValue("6")]))
print(compareAll([.stringValue("1"), .intValue(1)]))
```
// XCTAssertTrue failed
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 aInt), .intValue(let bInt)):
return aInt > bInt ? .intValue(aInt) : aInt < bInt ? .intValue(bInt) : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : aDouble < bDouble ? .doubleValue(bDouble) : nil
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? .stringValue(aString) : aString < bString ? .stringValue(bString) : nil
default:
return nil
}
}
func compareTwo(values: [Value]) -> Value? {
var max: Value?
for value in values {
if let max = max {
if let newMax = compareOne(a: value, b: max) {
max = newMax
}
} else {
max = value
}
}
return max
}
func compareThree(values: Value...) -> Value? {
var max: Value?
for value in values {
if let max = max {
if let newMax = compareOne(a: value, b: max) {
max = newMax
}
} else {
max = value
}
}
return max
}
func compareFour(values: [Value]) -> Value? {
var max: Value?
for value in values {
if let max = max {
if let newMax = compareOne(a: value, b: max) {
max = newMax
}
} else {
max = value
}
}
return max
}
```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 aInt), .intValue(let bInt)):
return aInt > bInt ? .intValue(aInt) : aInt < bInt ? .intValue(bInt) : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : aDouble < bDouble ? .doubleValue(bDouble) : nil
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? .stringValue(aString) : aString < bString ? .stringValue(bString) : nil
default:
return nil
}
}
// Create a function that takes an array of integers, floats, or strings representing
// real numbers, and returns the largest 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(values: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareTwo(values: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareTwo(values: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareTwo(values: [.stringValue("1"), .intValue(1)]) == nil
func compareTwo(values: [Value]) -> Value? {
var max: Value?
for value in values {
if let max = max {
if let newMax = compareOne(a: value, b: max) {
max = newMax
}
} else {
max = value
}
}
return max
}
// Create a function that takes a variable number of integers, floats, or strings representing
// real numbers, and returns the largest 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(values: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareThree(values: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareThree(values: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareThree(values: [.stringValue("1"), .intValue(1)]) == nil
func compareThree(values: Value...) -> Value? {
var max: Value?
for value in values {
if let max = max {
if let newMax = compareOne(a: value, b: max) {
max = newMax
}
} else {
max = value
}
}
return max
}
// Create a function that takes a variable number of integers, floats, or strings representing
// real numbers, and returns the largest 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(values: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareFour(values: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareFour(values: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareFour(values: [.stringValue("1"), .intValue(1)]) == nil
func compareFour(values: [Value]) -> Value? {
var max: Value?
for value in values {
if let max = max {
if let newMax = compareOne(a: value, b: max) {
max = newMax
}
} else {
max = value
}
}
return max
}
// Create a function that takes a variable number of integers, floats, or strings representing
// real numbers, and returns the largest 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(values: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareFive(values: [.intValue(1), .stringValue
max = newMax // cannot assign to value: 'max' is a 'let' constant
max = newMax // cannot assign to value: 'max' is a 'let' constant
max = newMax // cannot assign to value: 'max' is a 'let' constant
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 aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString.replacingOccurrences(of: ",", with: ".")) > Double(bString.replacingOccurrences(of: ",", with: ".")) ? a : Double(bString.replacingOccurrences(of: ",", with: ".")) > Double(aString.replacingOccurrences(of: ",", with: ".")) ? b : nil
default:
return nil
}
}
func compareTwo(a: [Value], b: [Value]) -> Value? {
guard a.count == b.count else { return nil }
for (aValue, bValue) in zip(a, b) {
if let result = compareOne(a: aValue, b: bValue) {
return result
}
}
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 aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString.replacingOccurrences(of: ",", with: ".")) > Double(bString.replacingOccurrences(of: ",", with: ".")) ? a : Double(bString.replacingOccurrences(of: ",", with: ".")) > Double(aString.replacingOccurrences(of: ",", with: ".")) ? b : nil
default:
return nil
}
}
// Create a function that takes arrays of 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: [1, 2, 3], b: [2.5, 3, 4]) == 2.5
// compareTwo(a: [1, 2, 3], b: ["2,3", "3", "4"]) == "2,3"
// compareTwo(a: ["5,1", "6", "7"], b: ["6"]) == "6"
// compareTwo(a: [1, 2, 3], b: [1, 2, 3]) == nil
func compareTwo(a: [Value], b: [Value]) -> Value? {
guard a.count == b.count else { return nil }
for (aValue, bValue) in zip(a, b) {
if let result = compareOne(a: aValue, b: bValue) {
return result
}
}
return nil
}
```
return Double(aString.replacingOccurrences(of: ",", with: ".")) > Double(bString.replacingOccurrences(of: ",", with: ".")) ? a : Double(bString.replacingOccurrences(of: ",", with: ".")) > Double(aString.replacingOccurrences(of: ",", with: ".")) ? b : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return Double(aString.replacingOccurrences(of: ",", with: ".")) > Double(bString.replacingOccurrences(of: ",", with: ".")) ? a : Double(bString.replacingOccurrences(of: ",", with: ".")) > Double(aString.replacingOccurrences(of: ",", with: ".")) ? b : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return Double(aString.replacingOccurrences(of: ",", with: ".")) > Double(bString.replacingOccurrences(of: ",", with: ".")) ? a : Double(bString.replacingOccurrences(of: ",", with: ".")) > Double(aString.replacingOccurrences(of: ",", with: ".")) ? b : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return Double(aString.replacingOccurrences(of: ",", with: ".")) > Double(bString.replacingOccurrences(of: ",", with: ".")) ? a : Double(bString.replacingOccurrences(of: ",", with: ".")) > Double(aString.replacingOccurrences(of: ",", with: ".")) ? b : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
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 ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)), (.doubleValue(let a), .doubleValue(let b)), (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)), (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
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)), (.doubleValue(let a), .doubleValue(let b)), (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
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)), (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)):
return a > b ? a : b
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)):
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:
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)): // pattern variable bound to type 'Int', expected type 'Double'
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)): // pattern variable bound to type 'Int', expected type 'String'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)): // pattern variable bound to type 'String', expected type 'Int'
case (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'Double', expected type 'String'
case (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'String', expected type 'Double'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'String', expected type 'Int'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'Int', expected type 'String'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // case is already handled by previous patterns; consider removing it
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // case is already handled by previous patterns; consider removing it
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // case is already handled by previous patterns; consider removing it
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // case is already handled by previous patterns; consider removing it
case (.intValue(let a), .intValue(let b)), (.doubleValue(let a), .doubleValue(let b)), (.stringValue(let a), .stringValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
case (.intValue(let a), .intValue(let b)), (.doubleValue(let a), .doubleValue(let b)), (.stringValue(let a), .stringValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)): // pattern variable bound to type 'Int', expected type 'Double'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'Int', expected type 'String'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'String', expected type 'Int'
case (.intValue(let a), .intValue(let b)), (.doubleValue(let a), .doubleValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
case (.intValue(let a), .intValue(let b)), (.doubleValue(let a), .doubleValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)): // pattern variable bound to type 'Double', expected type 'Int'
case (.intValue(let a), .doubleValue(let b)), (.doubleValue(let a), .intValue(let b)): // pattern variable bound to type 'Int', expected type 'Double'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'Int', expected type 'String'
case (.intValue(let a), .stringValue(let b)), (.stringValue(let a), .intValue(let b)), (.doubleValue(let a), .stringValue(let b)), (.stringValue(let a), .doubleValue(let b)): // pattern variable bound to type 'String', expected type 'Int'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b > a ? b : nil
case .doubleValue(let b):
return a > b ? a : b > a ? b : nil
case .stringValue(let b):
return a > b ? a : b > a ? b : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b > a ? b : nil
case .doubleValue(let b):
return a > b ? a : b > a ? b : nil
case .stringValue(let b):
return a > b ? a : b > a ? b : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b > a ? b : nil
case .doubleValue(let b):
return a > b ? a : b > a ? b : nil
case .stringValue(let b):
return a > b ? a : b > a ? b : nil
}
}
}
func compareTwo(a: Value, b: Value) -> [Value]? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .doubleValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .stringValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .doubleValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .stringValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .doubleValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .stringValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
}
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b > a ? b : nil
case .doubleValue(let b):
return a > b ? a : b > a ? b : nil
case .stringValue(let b):
return a > b ? a : b > a ? b : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b > a ? b : nil
case .doubleValue(let b):
return a > b ? a : b > a ? b : nil
case .stringValue(let b):
return a > b ? a : b > a ? b : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b > a ? b : nil
case .doubleValue(let b):
return a > b ? a : b > a ? b : nil
case .stringValue(let b):
return a > b ? a : b > a ? b : 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)) == [1, 2.5]
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == [1, "2,3"]
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == ["5,1", "6"]
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> [Value]? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .doubleValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .stringValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .doubleValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .stringValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .doubleValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : nil
case .stringValue(let b):
return a > b ? [a, b] : b > a ? [b, a] : 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)) == [1, 2.5, 2.5]
// compareThree(a: .intValue(1), b: .stringValue("2,3")) == [1, "2,3", "2,3"]
// compareThree(a: .stringValue("5,1"), b: .stringValue("6")) == ["5,1", "6", "6"]
// compareThree(a: .stringValue("1"), b: .intValue(1)) == nil
func compare
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'Int?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'Double?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'String?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'Int?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'Double?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // binary operator '>' cannot be applied to operands of type 'Double' and 'String'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'String?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'Int?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'Double?' to return type 'Value?'
return a > b ? a : b > a ? b : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? a : b > a ? b : nil // binary operator '>' cannot be applied to operands of type 'Double' and 'String'
return a > b ? a : b > a ? b : nil // cannot convert return expression of type 'String?' to return type 'Value?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Int' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Int>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Int' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Any>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Int' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Int' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Any>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Int' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Any>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Double>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Any>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // binary operator '>' cannot be applied to operands of type 'Double' and 'String'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Int' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Any>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'Double' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // binary operator '>' cannot be applied to operands of type 'Double' and 'String'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<Any>?' to return type '[Value]?'
return a > b ? [a, b] : b > a ? [b, a] : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert value of type 'String' to expected element type 'Array<Value>.ArrayLiteralElement' (aka 'Value')
return a > b ? [a, b] : b > a ? [b, a] : nil // cannot convert return expression of type 'Array<String>?' to return type '[Value]?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
}
}
// 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 {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > Double(b)! ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ? a : b
}
}
}
// 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 {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? a : b
case .stringValue(let b):
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b
case .doubleValue(let b):
return a > b ?
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? a : b // cannot convert value of type 'Double' to expected argument type 'Int'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > Double(b)! ? a : b // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > Double(b)! ? a : b // no exact matches in call to initializer
return a > Double(b)! ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > Double(b)! ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > Double(b)! ? a : b // cannot force unwrap value of non-optional type 'Double'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b)! ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > Double(b)! ? a : b // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > Double(b)! ? a : b // no exact matches in call to initializer
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? a : b // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > Double(b)! ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > Double(b)! ? a : b // cannot force unwrap value of non-optional type 'Double'
return a > Double(b.replacingOccurrences(of: ",", with: "."))! ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
if a == b {
return nil
} else if a > b {
return .intValue(a)
} else {
return .intValue(b)
}
case .doubleValue(let b):
if Double(a) == b {
return nil
} else if Double(a) > b {
return .doubleValue(Double(a))
} else {
return .doubleValue(b)
}
case .stringValue(let b):
if Double(a) == Double(b.replacingOccurrences(of: ",", with: ".")) {
return nil
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) {
return .doubleValue(Double(a))
} else {
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: ".")))
}
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
if a == Double(b) {
return nil
} else if a > Double(b) {
return .doubleValue(a)
} else {
return .doubleValue(Double(b))
}
case .doubleValue(let b):
if a == b {
return nil
} else if a > b {
return .doubleValue(a)
} else {
return .doubleValue(b)
}
case .stringValue(let b):
if a == Double(b.replacingOccurrences(of: ",", with: ".")) {
return nil
} else if a > Double(b.replacingOccurrences(of: ",", with: ".")) {
return .doubleValue(a)
} else {
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: ".")))
}
}
case .stringValue(let a):
switch b {
case .intValue(let b):
if Double(a) == Double(b) {
return nil
} else if Double(a) > Double(b) {
return .doubleValue(Double(a))
} else {
return .doubleValue(Double(b))
}
case .doubleValue(let b):
if Double(a) == b {
return nil
} else if Double(a) > b {
return .doubleValue(Double(a))
} else {
return .doubleValue(b)
}
case .stringValue(let b):
if Double(a) == Double(b.replacingOccurrences(of: ",", with: ".")) {
return nil
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) {
return .doubleValue(Double(a))
} else {
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: ".")))
}
}
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
if a == b {
return nil
} else if a > b {
return .intValue(a)
} else {
return .intValue(b)
}
case .doubleValue(let b):
if Double(a) == b {
return nil
} else if Double(a) > b {
return .doubleValue(Double(a))
} else {
return .doubleValue(b)
}
case .stringValue(let b):
if Double(a) == Double(b.replacingOccurrences(of: ",", with: ".")) {
return nil
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) {
return .doubleValue(Double(a))
} else {
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: ".")))
}
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
if a == Double(b) {
return nil
} else if a > Double(b) {
return .doubleValue(a)
} else {
return .doubleValue(Double(b))
}
case .doubleValue(let b):
if a == b {
return nil
} else if a > b {
return .doubleValue(a)
} else {
return .doubleValue(b)
}
case .stringValue(let b):
if a == Double(b.replacingOccurrences(of: ",", with: ".")) {
return nil
} else if a > Double(b.replacingOccurrences(of: ",", with: ".")) {
return .doubleValue(a)
} else {
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: ".")))
}
}
case .stringValue(let a):
switch b {
case .intValue(let b):
if Double(a) == Double(b) {
return nil
} else if Double(a) > Double(b) {
return .doubleValue(Double(a))
} else {
return .doubleValue(Double(b))
}
case .doubleValue(let b):
if Double(a) == b {
return nil
} else if Double(a) > b {
return .doubleValue(Double(a))
} else {
return .doubleValue(b)
}
case .stringValue(let b):
if Double(a) == Double(b.replacingOccurrences(of: ",", with: ".")) {
return nil
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) {
return .doubleValue(Double(a))
} else {
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: ".")))
}
}
}
}
// 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 {
case .intValue(let a):
switch b {
case .intValue(let b):
if a == b {
return nil
} else if a > b {
return .intValue(a)
} else {
return .intValue(b)
}
case .doubleValue(let b):
if Double(a) == b {
return nil
} else if Double(a) > b {
return .doubleValue(Double(a))
} else {
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: "."))) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
} else if a > Double(b.replacingOccurrences(of: ",", with: ".")) { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: "."))) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
} else if Double(a) > Double(b) { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return .doubleValue(Double(a)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
} else if Double(a) > b { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return .doubleValue(Double(a)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
} else if Double(a) > Double(b.replacingOccurrences(of: ",", with: ".")) { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return .doubleValue(Double(a)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return .doubleValue(Double(b.replacingOccurrences(of: ",", with: "."))) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
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 aInt), .intValue(let bInt)) where aInt > bInt:
return .intValue(aInt)
case (.intValue(let aInt), .intValue(let bInt)) where aInt < bInt:
return .intValue(bInt)
case (.intValue(let aInt), .intValue(let bInt)) where aInt == bInt:
return nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)) where aDouble > bDouble:
return .doubleValue(aDouble)
case (.doubleValue(let aDouble), .doubleValue(let bDouble)) where aDouble < bDouble:
return .doubleValue(bDouble)
case (.doubleValue(let aDouble), .doubleValue(let bDouble)) where aDouble == bDouble:
return nil
case (.stringValue(let aString), .stringValue(let bString)) where aString > bString:
return .stringValue(aString)
case (.stringValue(let aString), .stringValue(let bString)) where aString < bString:
return .stringValue(bString)
case (.stringValue(let aString), .stringValue(let bString)) where aString == bString:
return nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(aInt), .intValue(bInt)):
return aInt > bInt ? .intValue(aInt) : aInt < bInt ? .intValue(bInt) : nil
case let (.doubleValue(aDouble), .doubleValue(bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : aDouble < bDouble ? .doubleValue(bDouble) : nil
case let (.stringValue(aString), .stringValue(bString)):
return aString > bString ? .stringValue(aString) : aString < bString ? .stringValue(bString) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? .intValue(aInt) : aInt < bInt ? .intValue(bInt) : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : aDouble < bDouble ? .doubleValue(bDouble) : nil
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? .stringValue(aString) : aString < bString ? .stringValue(bString) : 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 aInt), .intValue(let bInt)) where aInt > bInt:
return .intValue(aInt)
case (.intValue(let aInt), .intValue(let bInt)) where aInt < bInt:
return .intValue(bInt)
case (.intValue(let aInt), .intValue(let bInt)) where aInt == bInt:
return nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)) where aDouble > bDouble:
return .doubleValue(aDouble)
case (.doubleValue(let aDouble), .doubleValue(let bDouble)) where aDouble < bDouble:
return .doubleValue(bDouble)
case (.doubleValue(let aDouble), .doubleValue(let bDouble)) where aDouble == bDouble:
return nil
case (.stringValue(let aString), .stringValue(let bString)) where aString > bString:
return .stringValue(aString)
case (.stringValue(let aString), .stringValue(let bString)) where aString < bString:
return .stringValue(bString)
case (.stringValue(let aString), .stringValue(let bString)) where aString == bString:
return 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(aInt), .intValue(bInt)):
return aInt > bInt ? .intValue(aInt) : aInt < bInt ? .intValue(bInt) : nil
case let (.doubleValue(aDouble), .doubleValue(bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : aDouble < bDouble ? .doubleValue(bDouble) : nil
case let (.stringValue(aString), .stringValue(bString)):
return aString > bString ? .stringValue(aString) : aString < bString ? .stringValue(bString) : 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 aInt), .intValue(let bInt)):
return aInt > bInt ? .intValue(aInt) : aInt < bInt ? .intValue(bInt) : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? .doubleValue(aDouble) : aDouble < bDouble ? .doubleValue(bDouble) : nil
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? .stringValue(aString) : aString < bString ? .stringValue(bString) : nil
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
if sum == n {
return true
}
return false
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
if sum == n {
return true
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1..<n {
if i % 2 == 0 {
sum += i
}
if sum == n {
return true
}
}
return false
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1..<n {
if i % 2 == 0 {
sum += i
}
if sum == n {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
if n <= 0 {
return false
}
if n % 2 != 0 {
return false
}
if n == 2 {
return true
}
let n = n/2
return isEqualToSumEven(n: 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 <= 0 {
return false
}
if n % 2 != 0 {
return false
}
if n == 2 {
return true
}
let n = n/2
return isEqualToSumEven(n: n)
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 0
while sum < n {
if i % 2 == 0 {
sum += i
}
i += 1
}
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 = 0
while sum < n {
if i % 2 == 0 {
sum += i
}
i += 1
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1..<n {
if i % 2 == 0 {
sum += i
}
if sum == n {
return true
}
}
return false
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1..<n {
if i % 2 == 0 {
sum += i
}
if sum == n {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
if n % 2 == 0 {
var sum = 0
for i in stride(from: 2, to: n, by: 2) {
if sum == n {
return true
} else if sum < n {
sum += i
} else {
break
}
}
}
return false
}
```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 % 2 == 0 {
var sum = 0
for i in stride(from: 2, to: n, by: 2) {
if sum == n {
return true
} else if sum < n {
sum += i
} else {
break
}
}
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// 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 {
// your code here
}
```
} // missing return in global function expected to return 'Bool'
func isEqualToSumEven(n: Int) -> Bool {
if n <= 0 {
return false
}
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
if i + j + k + l == n && i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
return true
}
}
}
}
}
return false
}
```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 <= 0 {
return false
}
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
if i + j + k + l == n && i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
return true
}
}
}
}
}
return false
}
```
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 0
while sum < n {
sum += i * 2
i += 1
}
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 = 0
while sum < n {
sum += i * 2
i += 1
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// your code here
var count = 0
var i = 2
while i < n {
if n % i == 0 {
count += 1
}
i += 2
}
return count == 4
}
```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 {
// your code here
var count = 0
var i = 2
while i < n {
if n % i == 0 {
count += 1
}
i += 2
}
return count == 4
}
```
// XCTAssertTrue failed
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 {
if n < 1 {
return 0
}
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 {
if n < 1 {
return 0
}
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
if n <= 0 {
return 1
}
var result = 1
for i in 1...n {
result *= factorial(i)
}
return result
}
func factorial(_ n: Int) -> Int {
if n <= 1 {
return 1
}
return n * factorial(n - 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 {
if n <= 0 {
return 1
}
var result = 1
for i in 1...n {
result *= factorial(i)
}
return result
}
func factorial(_ n: Int) -> Int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
```
func specialFactorial(n: Int) -> Int {
if n <= 1 {
return 1
}
return n * specialFactorial(n: n - 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 {
if n <= 1 {
return 1
}
return n * specialFactorial(n: n - 1)
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var factorial: Int = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```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 factorial: Int = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```
// 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 {
if n == 0 {
return 1
} else {
return n * specialFactorial(n: n - 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 {
if n == 0 {
return 1
} else {
return n * specialFactorial(n: n - 1)
}
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
```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 {
let words = text.components(separatedBy: .whitespacesAndNewlines)
let newString = words.joined(separator: "_")
var newString2 = newString.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString2 = newString2.replacingOccurrences(of: "__", with: "-")
newString
XCTAssertTrue(fixSpaces(text: "Example") == "Example") // cannot find 'fixSpaces' in scope
XCTAssertTrue(fixSpaces(text: "Mudasir Hanif ") == "Mudasir_Hanif_") // cannot find 'fixSpaces' in scope
XCTAssertTrue(fixSpaces(text: "Yellow Yellow Dirty Fellow") == "Yellow_Yellow__Dirty__Fellow") // cannot find 'fixSpaces' in scope
XCTAssertTrue(fixSpaces(text: "Exa mple") == "Exa-mple") // cannot find 'fixSpaces' in scope
XCTAssertTrue(fixSpaces(text: " Exa 1 2 2 mple") == "-Exa_1_2_2_mple") // cannot find 'fixSpaces' in scope
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 2 {
result += "-"
} else if count > 0 {
result += "_"
}
count = 0
result += String(char)
}
}
if count > 2 {
result += "-"
} else if count > 0 {
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 {
if count > 2 {
result += "-"
} else if count > 0 {
result += "_"
}
count = 0
result += String(char)
}
}
if count > 2 {
result += "-"
} else if count > 0 {
result += "_"
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let words = text.components(separatedBy: " ")
var result = ""
for (index, word) in words.enumerated() {
if index > 0 {
if word.isEmpty {
if words[index - 1].isEmpty {
result += "-"
} else {
result += "_"
}
} else {
result += "_"
}
}
result += word
}
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 {
let words = text.components(separatedBy: " ")
var result = ""
for (index, word) in words.enumerated() {
if index > 0 {
if word.isEmpty {
if words[index - 1].isEmpty {
result += "-"
} else {
result += "_"
}
} else {
result += "_"
}
}
result += word
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
if count > 2 {
result += "-"
} else {
result += "_"
}
} else {
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
if count > 2 {
result += "-"
} else {
result += "_"
}
} else {
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 {
count = 0
}
if count == 1 {
result += "_"
} else if count > 1 {
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 = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
count = 0
}
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let text = text.replacingOccurrences(of: " ", with: "-")
return text.replacingOccurrences(of: " ", with: "_")
}
```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 {
let text = text.replacingOccurrences(of: " ", with: "-")
return text.replacingOccurrences(of: " ", with: "_")
}
```
// 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 == 1 {
result.append("_")
} else if count == 2 {
result.append("-")
} else {
result.append(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 {
count = 0
}
if count == 1 {
result.append("_")
} else if count == 2 {
result.append("-")
} else {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let words = text.components(separatedBy: .whitespacesAndNewlines)
if words.isEmpty {
return text
}
var result = words[0]
for i in 1..<words.count {
if words[i].isEmpty {
if result.last == " " {
result.append("-")
} else {
result.append("_")
}
} else {
result.append("_")
result.append(words[i])
}
}
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 {
let words = text.components(separatedBy: .whitespacesAndNewlines)
if words.isEmpty {
return text
}
var result = words[0]
for i in 1..<words.count {
if words[i].isEmpty {
if result.last == " " {
result.append("-")
} else {
result.append("_")
}
} else {
result.append("_")
result.append(words[i])
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let newString = text.replacingOccurrences(of: " ", with: "-")
let finalString = newString.replacingOccurrences(of: " ", with: "_")
return finalString
}
```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 {
let newString = text.replacingOccurrences(of: " ", with: "-")
let finalString = newString.replacingOccurrences(of: " ", with: "_")
return finalString
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let newString = text.replacingOccurrences(of: " ", with: "-")
let finalString = newString.replacingOccurrences(of: " ", with: "_")
return finalString
}
```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 {
let newString = text.replacingOccurrences(of: " ", with: "-")
let finalString = newString.replacingOccurrences(of: " ", with: "_")
return finalString
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.split(separator: ".")
if file.count != 2 { return "No" }
if file[0].first != file[0].first?.uppercased() { return "No" }
if file[0].filter { $0.isNumber }.count > 3 { return "No" }
if !file[1].contains(["txt", "exe", "dll"]) { return "No" }
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let file = fileName.split(separator: ".")
if file.count != 2 { return "No" }
if file[0].first != file[0].first?.uppercased() { return "No" }
if file[0].filter { $0.isNumber }.count > 3 { return "No" }
if !file[1].contains(["txt", "exe", "dll"]) { return "No" }
return "Yes"
}
```
if file[0].first != file[0].first?.uppercased() { return "No" } // value of optional type 'String?' must be unwrapped to a value of type 'String'
if file[0].first != file[0].first?.uppercased() { return "No" } // type '((Substring.Element) throws -> Bool) throws -> Substring.Element?' (aka '((Character) throws -> Bool) throws -> Optional<Character>') cannot conform to 'StringProtocol'
if file[0].filter { $0.isNumber }.count > 3 { return "No" } // trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning
if !file[1].contains(["txt", "exe", "dll"]) { return "No" } // cannot convert value of type 'String' to expected element type 'Substring.Element' (aka 'Character')
if !file[1].contains(["txt", "exe", "dll"]) { return "No" } // cannot convert value of type 'String' to expected element type 'Substring.Element' (aka 'Character')
if !file[1].contains(["txt", "exe", "dll"]) { return "No" } // cannot convert value of type 'String' to expected element type 'Substring.Element' (aka 'Character')
func fileNameCheck(fileName: String) -> String {
let fileNameComponents = fileName.components(separatedBy: ".")
if fileNameComponents.count != 2 {
return "No"
}
let firstPart = fileNameComponents[0]
let secondPart = fileNameComponents[1]
if firstPart.isEmpty {
return "No"
}
let firstChar = firstPart.first!
if firstChar.isNumber || firstChar.isLowercase || firstChar.isUppercase {
return "No"
}
let digitsCount = firstPart.filter { $0.isNumber }.count
if digitsCount > 3 {
return "No"
}
let validExtensions = ["txt", "exe", "dll"]
if !validExtensions.contains(secondPart) {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileNameComponents = fileName.components(separatedBy: ".")
if fileNameComponents.count != 2 {
return "No"
}
let firstPart = fileNameComponents[0]
let secondPart = fileNameComponents[1]
if firstPart.isEmpty {
return "No"
}
let firstChar = firstPart.first!
if firstChar.isNumber || firstChar.isLowercase || firstChar.isUppercase {
return "No"
}
let digitsCount = firstPart.filter { $0.isNumber }.count
if digitsCount > 3 {
return "No"
}
let validExtensions = ["txt", "exe", "dll"]
if !validExtensions.contains(secondPart) {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.components(separatedBy: ".")
if file.count == 2 {
let first = file[0]
let second = file[1]
if first.range(of: "[a-zA-Z]+", options: .regularExpression) != nil {
if second == "txt" || second == "exe" || second == "dll" {
let count = first.filter { $0.isNumber }.count
if count <= 3 {
return "Yes"
}
}
}
}
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 {
let file = fileName.components(separatedBy: ".")
if file.count == 2 {
let first = file[0]
let second = file[1]
if first.range(of: "[a-zA-Z]+", options: .regularExpression) != nil {
if second == "txt" || second == "exe" || second == "dll" {
let count = first.filter { $0.isNumber }.count
if count <= 3 {
return "Yes"
}
}
}
}
return "No"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.split(separator: ".")
if file.count != 2 {
return "No"
}
let first = file[0]
let second = file[1]
if first.count == 0 || !first.starts(with: CharacterSet.letters) {
return "No"
}
if second != "txt" && second != "exe" && second != "dll" {
return "No"
}
let digits = first.filter { $0.isNumber }
if digits.count > 3 {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let file = fileName.split(separator: ".")
if file.count != 2 {
return "No"
}
let first = file[0]
let second = file[1]
if first.count == 0 || !first.starts(with: CharacterSet.letters) {
return "No"
}
if second != "txt" && second != "exe" && second != "dll" {
return "No"
}
let digits = first.filter { $0.isNumber }
if digits.count > 3 {
return "No"
}
return "Yes"
}
```
if first.count == 0 || !first.starts(with: CharacterSet.letters) { // instance method 'starts(with:)' requires that 'CharacterSet' conform to 'RegexComponent'
func fileNameCheck(fileName: String) -> String {
let fileNameComponents = fileName.components(separatedBy: ".")
if fileNameComponents.count != 2 {
return "No"
}
if fileNameComponents[0].count == 0 || !fileNameComponents[0].first!.isLetter {
return "No"
}
let digits = fileNameComponents[0].filter { $0.isNumber }
if digits.count > 3 {
return "No"
}
if !["txt", "exe", "dll"].contains(fileNameComponents[1]) {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileNameComponents = fileName.components(separatedBy: ".")
if fileNameComponents.count != 2 {
return "No"
}
if fileNameComponents[0].count == 0 || !fileNameComponents[0].first!.isLetter {
return "No"
}
let digits = fileNameComponents[0].filter { $0.isNumber }
if digits.count > 3 {
return "No"
}
if !["txt", "exe", "dll"].contains(fileNameComponents[1]) {
return "No"
}
return "Yes"
}
```
func fileNameCheck(fileName: String) -> String {
let fileNameSplit = fileName.split(separator: ".")
if fileNameSplit.count == 2 {
if fileNameSplit[0].count > 0 {
if fileNameSplit[1] == "txt" || fileNameSplit[1] == "exe" || fileNameSplit[1] == "dll" {
let fileNameSplit2 = Array(fileNameSplit[0])
var count = 0
for i in fileNameSplit2 {
if i.isNumber {
count += 1
}
}
if count < 4 {
return "Yes"
}
}
}
}
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 {
let fileNameSplit = fileName.split(separator: ".")
if fileNameSplit.count == 2 {
if fileNameSplit[0].count > 0 {
if fileNameSplit[1] == "txt" || fileNameSplit[1] == "exe" || fileNameSplit[1] == "dll" {
let fileNameSplit2 = Array(fileNameSplit[0])
var count = 0
for i in fileNameSplit2 {
if i.isNumber {
count += 1
}
}
if count < 4 {
return "Yes"
}
}
}
}
return "No"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.components(separatedBy: ".")
if file.count != 2 {
return "No"
}
if file[0].count > 3 {
return "No"
}
if file[1].count > 3 {
return "No"
}
if !file[0].contains("0123456789") {
return "No"
}
if file[1] == "txt" || file[1] == "exe" || file[1] == "dll" {
return "Yes"
}
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 {
let file = fileName.components(separatedBy: ".")
if file.count != 2 {
return "No"
}
if file[0].count > 3 {
return "No"
}
if file[1].count > 3 {
return "No"
}
if !file[0].contains("0123456789") {
return "No"
}
if file[1] == "txt" || file[1] == "exe" || file[1] == "dll" {
return "Yes"
}
return "No"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.components(separatedBy: ".")
if file.count > 2 {
return "No"
}
let firstPart = file[0]
let secondPart = file[1]
if secondPart == "txt" || secondPart == "exe" || secondPart == "dll" {
for i in firstPart {
if i == "." {
return "No"
}
if i >= "0" && i <= "9" {
return "No"
}
if i >= "a" && i <= "z" {
return "Yes"
}
if i >= "A" && i <= "Z" {
return "Yes"
}
}
}
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 {
let file = fileName.components(separatedBy: ".")
if file.count > 2 {
return "No"
}
let firstPart = file[0]
let secondPart = file[1]
if secondPart == "txt" || secondPart == "exe" || secondPart == "dll" {
for i in firstPart {
if i == "." {
return "No"
}
if i >= "0" && i <= "9" {
return "No"
}
if i >= "a" && i <= "z" {
return "Yes"
}
if i >= "A" && i <= "Z" {
return "Yes"
}
}
}
return "No"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.split(separator: ".")
if file.count != 2 { return "No" }
if file[0].isEmpty { return "No" }
if file[0].first!.isLetter {
if file[0].dropFirst().allSatisfy({ $0.isNumber }) { return "No" }
if file[1] == "txt" || file[1] == "exe" || file[1] == "dll" { return "Yes" }
}
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 {
let file = fileName.split(separator: ".")
if file.count != 2 { return "No" }
if file[0].isEmpty { return "No" }
if file[0].first!.isLetter {
if file[0].dropFirst().allSatisfy({ $0.isNumber }) { return "No" }
if file[1] == "txt" || file[1] == "exe" || file[1] == "dll" { return "Yes" }
}
return "No"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let file = fileName.split(separator: ".")
let fileExtension = file[1]
let fileExtensionArray = fileExtension.split(separator: "")
let fileExtensionString = String(fileExtension)
if file.count == 2 {
if fileExtensionArray.count == 3 {
if fileExtensionString == "txt" || fileExtensionString == "exe" || fileExtensionString == "dll" {
if file.first?.first?.isLetter ?? false {
if file.first!.count > 0 {
if file.first!.count < 4 {
return "Yes"
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
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 {
let file = fileName.split(separator: ".")
let fileExtension = file[1]
let fileExtensionArray = fileExtension.split(separator: "")
let fileExtensionString = String(fileExtension)
if file.count == 2 {
if fileExtensionArray.count == 3 {
if fileExtensionString == "txt" || fileExtensionString == "exe" || fileExtensionString == "dll" {
if file.first?.first?.isLetter ?? false {
if file.first!.count > 0 {
if file.first!.count < 4 {
return "Yes"
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result
}
func isPrime(number: Int) -> Bool {
if number == 1 { return false }
if number == 2 { return true }
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result
}
func isPrime(number: Int) -> Bool {
if number == 1 { return false }
if number == 2 { return true }
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
let wordLength = word.count
if isPrime(wordLength) {
result += word
result += " "
}
}
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.split(separator: " ")
var result = ""
for word in words {
let wordLength = word.count
if isPrime(wordLength) {
result += word
result += " "
}
}
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.components(separatedBy: " ")
var primeWords = [String]()
for word in words {
if isPrime(number: word.count) {
primeWords.append(word)
}
}
return primeWords.joined(separator: " ")
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var primeWords = [String]()
for word in words {
if isPrime(number: word.count) {
primeWords.append(word)
}
}
return primeWords.joined(separator: " ")
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = [String]()
for word in words {
if isPrime(word.count) {
primeWords.append(String(word))
}
}
return primeWords.joined(separator: " ")
}
func isPrime(_ num: Int) -> Bool {
if num == 1 { return false }
for i in 2..<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.split(separator: " ")
var primeWords = [String]()
for word in words {
if isPrime(word.count) {
primeWords.append(String(word))
}
}
return primeWords.joined(separator: " ")
}
func isPrime(_ num: Int) -> Bool {
if num == 1 { return false }
for i in 2..<num {
if num % i == 0 { return false }
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
return words.filter { isPrime($0.count) }.joined(separator: " ")
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 { 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.components(separatedBy: " ")
return words.filter { isPrime($0.count) }.joined(separator: " ")
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 { 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: " ")
let primeWords = words.filter { $0.count.isPrime }
return primeWords.joined(separator: " ")
}
```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 primeWords = words.filter { $0.count.isPrime }
return primeWords.joined(separator: " ")
}
```
let primeWords = words.filter { $0.count.isPrime } // value of type 'Int' has no member 'isPrime'
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
let primes = Array(2...100).filter { isPrime($0) }
var result = ""
for word in words {
if primes.contains(word.count) {
result.append(word + " ")
}
}
return String(result.dropLast())
}
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 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 = Array(2...100).filter { isPrime($0) }
var result = ""
for word in words {
if primes.contains(word.count) {
result.append(word + " ")
}
}
return String(result.dropLast())
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
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, 101]
let filteredWords = words.filter { word in
let wordLength = word.count
return primes.contains(wordLength)
}
let result = filteredWords.joined(separator: " ")
return result
}
```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, 101]
let filteredWords = words.filter { word in
let wordLength = word.count
return primes.contains(wordLength)
}
let result = filteredWords.joined(separator: " ")
return result
}
wordsInSentence(sentence: "This is a test")
wordsInSentence(sentence: "lets go for swimming")
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
return words.filter { word in
let length = word.count
if length == 1 {
return false
}
for i in 2...Int(sqrt(Double(length))) {
if length % i == 0 {
return false
}
}
return true
}.joined(separator: " ")
}
```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: " ")
return words.filter { word in
let length = word.count
if length == 1 {
return false
}
for i in 2...Int(sqrt(Double(length))) {
if length % i == 0 {
return false
}
}
return true
}.joined(separator: " ")
}
```
// Fatal error: Range requires lowerBound <= upperBound
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/").map { Int($0) }
let n = n.split(separator: "/").map { Int($0) }
let x = x[0] * n[1]
let n = x[1] * n[0]
return x % 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) }
let x = x[0] * n[1]
let n = x[1] * n[0]
return x % n == 0
}
```
let x = x[0] * n[1] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let x = x[0] * n[1] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func simplify(x: String, n: String) -> Bool {
let x = x.components(separatedBy: "/")
let n = n.components(separatedBy: "/")
let xNumerator = Int(x[0]) ?? 0
let xDenominator = Int(x[1]) ?? 0
let nNumerator = Int(n[0]) ?? 0
let nDenominator = Int(n[1]) ?? 0
let x = xNumerator * nDenominator
let y = xDenominator * nNumerator
return x == y
}
```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.components(separatedBy: "/")
let n = n.components(separatedBy: "/")
let xNumerator = Int(x[0]) ?? 0
let xDenominator = Int(x[1]) ?? 0
let nNumerator = Int(n[0]) ?? 0
let nDenominator = Int(n[1]) ?? 0
let x = xNumerator * nDenominator
let y = xDenominator * nNumerator
return x == y
}
```
let x = xNumerator * nDenominator // invalid redeclaration of 'x'
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.split(separator: "/")[0])!
let xDenominator = Int(x.split(separator: "/")[1])!
let nNumerator = Int(n.split(separator: "/")[0])!
let nDenominator = Int(n.split(separator: "/")[1])!
let xNum = xNumerator * nNumerator
let xDen = xDenominator * nDenominator
if (xNum % xDen == 0) {
return true
}
return false
}
```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.split(separator: "/")[0])!
let xDenominator = Int(x.split(separator: "/")[1])!
let nNumerator = Int(n.split(separator: "/")[0])!
let nDenominator = Int(n.split(separator: "/")[1])!
let xNum = xNumerator * nNumerator
let xDen = xDenominator * nDenominator
if (xNum % xDen == 0) {
return true
}
return 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 xTimesN = xNumerator * nNumerator
let xTimesNDenominator = xDenominator * nDenominator
if xTimesN % xTimesNDenominator == 0 {
return true
} else {
return false
}
}
```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 xTimesN = xNumerator * nNumerator
let xTimesNDenominator = xDenominator * nDenominator
if xTimesN % xTimesNDenominator == 0 {
return true
} else {
return false
}
}
```
func simplify(x: String, n: String) -> Bool {
let xNum = x.split(separator: "/")[0]
let xDen = x.split(separator: "/")[1]
let nNum = n.split(separator: "/")[0]
let nDen = n.split(separator: "/")[1]
let xMulN = (Int(xNum)! * Int(nNum)!) / (Int(xDen)! * Int(nDen)!)
return xMulN % 1 == 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 xNum = x.split(separator: "/")[0]
let xDen = x.split(separator: "/")[1]
let nNum = n.split(separator: "/")[0]
let nDen = n.split(separator: "/")[1]
let xMulN = (Int(xNum)! * Int(nNum)!) / (Int(xDen)! * Int(nDen)!)
return xMulN % 1 == 0
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNum = Int(x.split(separator: "/").first!)
let xDen = Int(x.split(separator: "/").last!)
let nNum = Int(n.split(separator: "/").first!)
let nDen = Int(n.split(separator: "/").last!)
let xNumN = xNum! * nNum!
let xDenN = xDen! * nDen!
return xNumN % xDenN == 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 xNum = Int(x.split(separator: "/").first!)
let xDen = Int(x.split(separator: "/").last!)
let nNum = Int(n.split(separator: "/").first!)
let nDen = Int(n.split(separator: "/").last!)
let xNumN = xNum! * nNum!
let xDenN = xDen! * nDen!
return xNumN % xDenN == 0
}
```
func simplify(x: String, n: String) -> Bool {
let xNum = x.split(separator: "/")[0]
let xDen = x.split(separator: "/")[1]
let nNum = n.split(separator: "/")[0]
let nDen = n.split(separator: "/")[1]
let xNumInt = Int(xNum)!
let xDenInt = Int(xDen)!
let nNumInt = Int(nNum)!
let nDenInt = Int(nDen)!
if (xNumInt * nDenInt) == (xDenInt * nNumInt) {
return true
} else {
return false
}
}
```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 xNum = x.split(separator: "/")[0]
let xDen = x.split(separator: "/")[1]
let nNum = n.split(separator: "/")[0]
let nDen = n.split(separator: "/")[1]
let xNumInt = Int(xNum)!
let xDenInt = Int(xDen)!
let nNumInt = Int(nNum)!
let nDenInt = Int(nDen)!
if (xNumInt * nDenInt) == (xDenInt * nNumInt) {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.split(separator: "/")[0])!
let xDenominator = Int(x.split(separator: "/")[1])!
let nNumerator = Int(n.split(separator: "/")[0])!
let nDenominator = Int(n.split(separator: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
return xProduct % nProduct == 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.split(separator: "/")[0])!
let xDenominator = Int(x.split(separator: "/")[1])!
let nNumerator = Int(n.split(separator: "/")[0])!
let nDenominator = Int(n.split(separator: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
return xProduct % nProduct == 0
}
```
// 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 xMultiplied = xNumerator * nDenominator
let nMultiplied = nNumerator * xDenominator
return xMultiplied % nMultiplied == 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 xMultiplied = xNumerator * nDenominator
let nMultiplied = nNumerator * xDenominator
return xMultiplied % nMultiplied == 0
}
```
// 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 xWholeNumber = xNumerator / xDenominator
let nWholeNumber = nNumerator / nDenominator
if xWholeNumber * nWholeNumber == 0 {
return false
}
let xRemainder = xNumerator % xDenominator
let nRemainder = nNumerator % nDenominator
return xRemainder * nDenominator == nRemainder * 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 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 xWholeNumber = xNumerator / xDenominator
let nWholeNumber = nNumerator / nDenominator
if xWholeNumber * nWholeNumber == 0 {
return false
}
let xRemainder = xNumerator % xDenominator
let nRemainder = nNumerator % nDenominator
return xRemainder * nDenominator == nRemainder * xDenominator
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { $0.sum < $1.sum }
return sorted
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { $0.sum < $1.sum }
return sorted
}
```
let sorted = nums.sorted { $0.sum < $1.sum } // cannot infer type of closure parameter '$0' without a type annotation
let sorted = nums.sorted { $0.sum < $1.sum } // type '(_, _) -> Bool' cannot conform to 'SortComparator'
let sorted = nums.sorted { $0.sum < $1.sum } // cannot infer type of closure parameter '$1' without a type annotation
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
if sumOfDigits($0) == sumOfDigits($1) {
return nums.index(of: $0) < nums.index(of: $1)
} else {
return sumOfDigits($0) < sumOfDigits($1)
}
}
}
func sumOfDigits(_ number: Int) -> Int {
let numberString = String(number)
return numberString.reduce(0, { $0 + Int(String($1))! })
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
if sumOfDigits($0) == sumOfDigits($1) {
return nums.index(of: $0) < nums.index(of: $1)
} else {
return sumOfDigits($0) < sumOfDigits($1)
}
}
}
func sumOfDigits(_ number: Int) -> Int {
let numberString = String(number)
return numberString.reduce(0, { $0 + Int(String($1))! })
}
```
return nums.index(of: $0) < nums.index(of: $1) // value of optional type 'Array<Int>.Index?' (aka 'Optional<Int>') must be unwrapped to a value of type 'Array<Int>.Index' (aka 'Int')
return nums.index(of: $0) < nums.index(of: $1) // value of optional type 'Array<Int>.Index?' (aka 'Optional<Int>') must be unwrapped to a value of type 'Array<Int>.Index' (aka 'Int')
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { $0.sum < $1.sum }
return sorted
}
extension Int {
var sum: Int {
var sum = 0
var number = self
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { $0.sum < $1.sum }
return sorted
}
extension Int {
var sum: Int {
var sum = 0
var number = self
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort(by: { (a, b) -> Bool in
let sumA = String(a).reduce(0, { $0 + Int(String($1))! })
let sumB = String(b).reduce(0, { $0 + Int(String($1))! })
return sumA < sumB
})
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort(by: { (a, b) -> Bool in
let sumA = String(a).reduce(0, { $0 + Int(String($1))! })
let sumB = String(b).reduce(0, { $0 + Int(String($1))! })
return sumA < sumB
})
return result
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func orderByPoints(nums: [Int]) -> [Int] {
// your code here
return nums
}
```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
return nums
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { (a, b) -> Bool in
let aSum = sum(a)
let bSum = sum(b)
if aSum != bSum {
return aSum < bSum
}
return a < b
})
}
func sum(_ num: Int) -> Int {
return String(num).compactMap { Int(String($0)) }.reduce(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(by: { (a, b) -> Bool in
let aSum = sum(a)
let bSum = sum(b)
if aSum != bSum {
return aSum < bSum
}
return a < b
})
}
func sum(_ num: Int) -> Int {
return String(num).compactMap { Int(String($0)) }.reduce(0, +)
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort(by: { (a, b) -> Bool in
let aSum = String(a).reduce(0, { (result, element) -> Int in
return result + Int(String(element))!
})
let bSum = String(b).reduce(0, { (result, element) -> Int in
return result + Int(String(element))!
})
if aSum == bSum {
return a < b
}
return aSum < bSum
})
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort(by: { (a, b) -> Bool in
let aSum = String(a).reduce(0, { (result, element) -> Int in
return result + Int(String(element))!
})
let bSum = String(b).reduce(0, { (result, element) -> Int in
return result + Int(String(element))!
})
if aSum == bSum {
return a < b
}
return aSum < bSum
})
return result
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func orderByPoints(nums: [Int]) -> [Int] {
var sortedArray = nums
sortedArray.sort { (num1, num2) -> Bool in
let sum1 = getSumOfDigits(number: num1)
let sum2 = getSumOfDigits(number: num2)
if sum1 == sum2 {
return num1 > num2
} else {
return sum1 > sum2
}
}
return sortedArray
}
func getSumOfDigits(number: Int) -> Int {
let numberString = String(number)
let numberArray = numberString.map { Int(String($0))! }
return numberArray.reduce(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] {
var sortedArray = nums
sortedArray.sort { (num1, num2) -> Bool in
let sum1 = getSumOfDigits(number: num1)
let sum2 = getSumOfDigits(number: num2)
if sum1 == sum2 {
return num1 > num2
} else {
return sum1 > sum2
}
}
return sortedArray
}
func getSumOfDigits(number: Int) -> Int {
let numberString = String(number)
let numberArray = numberString.map { Int(String($0))! }
return numberArray.reduce(0, +)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted { (num1, num2) -> Bool in
let sum1 = num1.digits().reduce(0, { $0 + $1 })
let sum2 = num2.digits().reduce(0, { $0 + $1 })
if sum1 == sum2 {
return num1 < num2
}
return sum1 < sum2
}
}
```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 { (num1, num2) -> Bool in
let sum1 = num1.digits().reduce(0, { $0 + $1 })
let sum2 = num2.digits().reduce(0, { $0 + $1 })
if sum1 == sum2 {
return num1 < num2
}
return sum1 < sum2
}
}
```
let sum1 = num1.digits().reduce(0, { $0 + $1 }) // value of type 'Int' has no member 'digits'
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
let sorted = nums.sorted(by: { (a, b) -> Bool in
let aSum = a.digits.reduce(0, +)
let bSum = b.digits.reduce(0, +)
if aSum == bSum {
return nums.index(of: a)! < nums.index(of: b)!
}
return aSum < bSum
})
return sorted
}
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] {
var nums = nums
let sorted = nums.sorted(by: { (a, b) -> Bool in
let aSum = a.digits.reduce(0, +)
let bSum = b.digits.reduce(0, +)
if aSum == bSum {
return nums.index(of: a)! < nums.index(of: b)!
}
return aSum < bSum
})
return sorted
}
extension Int {
var digits: [Int] {
var digits = [Int]()
var number = self
while number > 0 {
digits.append(number % 10)
number /= 10
}
return digits
}
}
```
var nums = nums // variable 'nums' was never mutated; consider changing to 'let' constant
return nums.index(of: a)! < nums.index(of: b)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
return nums.index(of: a)! < nums.index(of: b)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.filter { $0 > 10 && $0 % 10 % 2 == 1 && $0 / 10 % 2 == 1}.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.filter { $0 > 10 && $0 % 10 % 2 == 1 && $0 / 10 % 2 == 1}.count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return 0
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return 0
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
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 % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return 0
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return 0
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.filter { $0 > 10 && ($0 % 10) % 2 == 1 && $0 / 10 % 2 == 1 && $0 > 0}.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.filter { $0 > 10 && ($0 % 10) % 2 == 1 && $0 / 10 % 2 == 1 && $0 > 0}.count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return 0
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return 0
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
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 % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.filter { $0 > 10 && ($0 % 10) % 2 == 1 && ($0 / 10) % 2 == 1 }.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.filter { $0 > 10 && ($0 % 10) % 2 == 1 && ($0 / 10) % 2 == 1 }.count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
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 % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
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 % 2 != 0 && num % 10 != 0 {
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...a.count - 1 {
for j in i + 1...a.count - 1 {
for k in j + 1...a.count - 1 {
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...a.count - 1 {
for j in i + 1...a.count - 1 {
for k in j + 1...a.count - 1 {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
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
}
```
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-3) {
for j in (i+1)..<(n-1) {
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-3) {
for j in (i+1)..<(n-1) {
for k in (j+1)...n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Index out of range
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 - 3 {
for j in i + 1...n - 2 {
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 - 3 {
for j in i + 1...n - 2 {
for k in j + 1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
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 - 3 {
for j in i + 1...n - 2 {
for k in j + 1...n - 1 {
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 - 3 {
for j in i + 1...n - 2 {
for k in j + 1...n - 1 {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
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...a.count - 3 {
for j in i+1...a.count - 2 {
for k in j+1...a.count - 1 {
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...a.count - 3 {
for j in i+1...a.count - 2 {
for k in j+1...a.count - 1 {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
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-3) {
for j in (i+1)...(n-2) {
for k in (j+1)...(n-1) {
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-3) {
for j in (i+1)...(n-2) {
for k in (j+1)...(n-1) {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
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..<(a.count - 2) {
for j in (i+1)..<(a.count - 1) {
for k in (j+1)..<a.count {
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..<(a.count - 2) {
for j in (i+1)..<(a.count - 1) {
for k in (j+1)..<a.count {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
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
}
```
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 - 2) {
for j in i + 1..<(n - 1) {
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 - 2) {
for j in i + 1..<(n - 1) {
for k in j + 1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func sortedListSum(lst: [String]) -> [String] {
return lst.filter { $0.count % 2 == 0 }.sorted { $0.count < $1.count || ($0.count == $1.count && $0 < $1) }
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
return lst.filter { $0.count % 2 == 0 }.sorted { $0.count < $1.count || ($0.count == $1.count && $0 < $1) }
}
```
func sortedListSum(lst: [String]) -> [String] {
// your code here
return []
}
```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] {
// your code here
return []
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
lst.filter { $0.count % 2 == 0 }
.sorted { $0.count < $1.count }
.sorted { $0 < $1 }
}
```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] {
lst.filter { $0.count % 2 == 0 }
.sorted { $0.count < $1.count }
.sorted { $0 < $1 }
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
let sortedList = lst.filter { $0.count % 2 == 0 }
return sortedList.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] {
let sortedList = lst.filter { $0.count % 2 == 0 }
return sortedList.sorted(by: { $0.count < $1.count})
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
let result = lst.filter { $0.count % 2 == 0 }.sorted()
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] {
let result = lst.filter { $0.count % 2 == 0 }.sorted()
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted {
if $0.count < $1.count {
return true
} else if $0.count > $1.count {
return false
} else {
return $0 < $1
}
}
sorted = sorted.filter { $0.count % 2 == 0 }
return 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 sorted = lst.sorted {
if $0.count < $1.count {
return true
} else if $0.count > $1.count {
return false
} else {
return $0 < $1
}
}
sorted = sorted.filter { $0.count % 2 == 0 }
return sorted
}
```
func sortedListSum(lst: [String]) -> [String] {
lst.filter { $0.count % 2 == 0 }
.sorted {
$0.count == $1.count ? $0 < $1 : $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] {
lst.filter { $0.count % 2 == 0 }
.sorted {
$0.count == $1.count ? $0 < $1 : $0.count < $1.count
}
}
```
func sortedListSum(lst: [String]) -> [String] {
let sortedLst = lst.sorted { $0.count < $1.count || ($0.count == $1.count && $0 < $1) }
let filteredLst = sortedLst.filter { $0.count % 2 == 0 }
return filteredLst
}
```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 sortedLst = lst.sorted { $0.count < $1.count || ($0.count == $1.count && $0 < $1) }
let filteredLst = sortedLst.filter { $0.count % 2 == 0 }
return filteredLst
}
```
func sortedListSum(lst: [String]) -> [String] {
return lst.filter { $0.count % 2 == 0 }.sorted { $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] {
return lst.filter { $0.count % 2 == 0 }.sorted { $0.count < $1.count }
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
return lst.filter { $0.count % 2 == 0 }.sorted { $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] {
return lst.filter { $0.count % 2 == 0 }.sorted { $0.count < $1.count }
}
```
// 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 {
var isPrime = true
for i in 2...n-1 {
if n % i == 0 {
isPrime = false
break
}
}
return isPrime ? x : y
}
```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 {
var isPrime = true
for i in 2...n-1 {
if n % i == 0 {
isPrime = false
break
}
}
return isPrime ? x : y
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
```
if isPrime(n: n) { // cannot find 'isPrime' in scope
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
if n < 2 {
isPrime = false
}
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
}
else {
return y
}
}
```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 {
var isPrime = true
if n < 2 {
isPrime = false
}
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
}
else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2...(n-1) {
if n % i == 0 {
isPrime = false
break
}
}
if isPrime {
return x
} else {
return y
}
}
```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 {
var isPrime = true
for i in 2...(n-1) {
if n % i == 0 {
isPrime = false
break
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2 ..< n {
if n % i == 0 {
isPrime = false
}
}
if isPrime == true {
return x
} else {
return y
}
}
```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 {
var isPrime = true
for i in 2 ..< n {
if n % i == 0 {
isPrime = false
}
}
if isPrime == true {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
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 {
if n % 2 == 0 {
return y
} else {
return x
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n % 2 == 0 {
return y
} else {
return x
}
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime: Bool = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
break
}
}
if isPrime {
return x
} else {
return y
}
}
```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 {
var isPrime: Bool = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
break
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func doubleTheDifference(lst: [Double]) -> Int {
let oddNumbers = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
let oddNumbersSquared = oddNumbers.map { $0 * $0 }
return oddNumbersSquared.reduce(0, +)
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
let oddNumbers = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
let oddNumbersSquared = oddNumbers.map { $0 * $0 }
return oddNumbersSquared.reduce(0, +)
}
```
return oddNumbersSquared.reduce(0, +) // cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Double) throws -> Int'
func doubleTheDifference(lst: [Double]) -> Int {
let oddNumbers = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
let oddNumbersSum = oddNumbers.map { $0 * $0 }.reduce(0, +)
return oddNumbersSum
}
```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 {
let oddNumbers = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
let oddNumbersSum = oddNumbers.map { $0 * $0 }.reduce(0, +)
return oddNumbersSum
}
```
return oddNumbersSum // cannot convert return expression of type 'Double' to return type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.isInteger {
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.isInteger {
sum += Int(num * num)
}
}
return sum
}
```
if num > 0 && num.isInteger { // value of type 'Double' has no member 'isInteger'
func doubleTheDifference(lst: [Double]) -> Int {
let odd = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
let sum = odd.reduce(0, { $0 + $1 * $1 })
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 {
let odd = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
let sum = odd.reduce(0, { $0 + $1 * $1 })
return sum
}
```
return sum // cannot convert return expression of type 'Double' to return type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
let oddNums = lst.filter { $0 % 2 != 0 }
let oddNumsSquared = oddNums.map { $0 * $0 }
let sum = oddNumsSquared.reduce(0) { $0 + $1 }
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 {
let oddNums = lst.filter { $0 % 2 != 0 }
let oddNumsSquared = oddNums.map { $0 * $0 }
let sum = oddNumsSquared.reduce(0) { $0 + $1 }
return sum
}
```
let oddNums = lst.filter { $0 % 2 != 0 } // '%' is unavailable: For floating point numbers use truncatingRemainder instead
return sum // cannot convert return expression of type 'Double' to return type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
let odd = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 && $0 % 2 != 0 }
return odd.map { $0 * $0 }.reduce(0, +)
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
let odd = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 && $0 % 2 != 0 }
return odd.map { $0 * $0 }.reduce(0, +)
}
```
let odd = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 && $0 % 2 != 0 } // '%' is unavailable: For floating point numbers use truncatingRemainder instead
return odd.map { $0 * $0 }.reduce(0, +) // cannot convert value of type 'Double' to closure result type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum: Int = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 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: Int = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(num * num)
}
}
return sum
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
return lst.filter{ $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0}.map{ Int($0 * $0)}.reduce(0, +)
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
return lst.filter{ $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0}.map{ Int($0 * $0)}.reduce(0, +)
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
// your code here
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 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 {
// your code here
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(num * num)
}
}
return sum
}
```
// XCTAssertTrue failed
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(guess[i] - game[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(guess[i] - game[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(guess[i] - game[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(guess[i] - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(guess[i] - game[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(guess[i] - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(guess[i] - game[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(guess[i] - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(guess[i] - game[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(guess[i] - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(guess[i] - game[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(guess[i] - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.components(separatedBy: " ")
let classString = classArray.joined(separator: "_")
var extensionArray = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionString = ""
var extensionStrength = 0
var extensionName = ""
for extension in extensionArray {
let extensionArray = extension.components(separatedBy: " ")
let extensionString = extensionArray.joined(separator: "_")
var extensionStrength = 0
var extensionName = ""
for letter in extensionString {
if letter == letter.uppercased() {
extensionStrength += 1
} else {
extensionStrength -= 1
}
}
if extensionStrength > extensionStrength {
extensionStrength = extensionStrength
extensionName = extensionString
}
}
return "\(classString).\(extensionName)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.components(separatedBy: " ")
let classString = classArray.joined(separator: "_")
var extensionArray = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionString = ""
var extensionStrength = 0
var extensionName = ""
for extension in extensionArray {
let extensionArray = extension.components(separatedBy: " ")
let extensionString = extensionArray.joined(separator: "_")
var extensionStrength = 0
var extensionName = ""
for letter in extensionString {
if letter == letter.uppercased() {
extensionStrength += 1
} else {
extensionStrength -= 1
}
}
if extensionStrength > extensionStrength {
extensionStrength = extensionStrength
extensionName = extensionString
}
}
return "\(classString).\(extensionName)"
}
```
for extension in extensionArray { // expected '{' to start the body of for-each loop
for extension in extensionArray { // expected pattern
for extension in extensionArray { // expected Sequence expression for for-each loop
let extensionArray = extension.components(separatedBy: " ") // expected '{' in extension
let extensionArray = extension.components(separatedBy: " ") // expected initial value after '='
let extensionArray = extension.components(separatedBy: " ") // expected type name in extension declaration
let extensionArray = extension.components(separatedBy: " ") // declaration is only valid at file scope
let extensionArray = extension.components(separatedBy: " ") // consecutive statements on a line must be separated by ';'
func Strongest_Extension(className: String, extensions: [String]) -> String {
// your code here
}
```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 {
// your code here
}
```
} // missing return in global function expected to return 'String'
func Strongest_Extension(className: String, extensions: [String]) -> String {
// your code here
let classArray = className.map { String($0) }
var cap = 0
var sm = 0
var extensionArray = [String]()
for i in classArray {
if i.uppercased() == i {
cap += 1
} else if i.lowercased() == i {
sm += 1
}
}
let extensionArray = extensions.map { $0.map { String($0) } }
for i in extensionArray {
var cap = 0
var sm = 0
for j in i {
if j.uppercased() == j {
cap += 1
} else if j.lowercased() == j {
sm += 1
}
}
let fraction = cap - sm
if fraction == cap {
extensionArray.append(i.joined())
}
}
return "\(className).\(extensionArray[0])"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
// your code here
let classArray = className.map { String($0) }
var cap = 0
var sm = 0
var extensionArray = [String]()
for i in classArray {
if i.uppercased() == i {
cap += 1
} else if i.lowercased() == i {
sm += 1
}
}
let extensionArray = extensions.map { $0.map { String($0) } }
for i in extensionArray {
var cap = 0
var sm = 0
for j in i {
if j.uppercased() == j {
cap += 1
} else if j.lowercased() == j {
sm += 1
}
}
let fraction = cap - sm
if fraction == cap {
extensionArray.append(i.joined())
}
}
return "\(className).\(extensionArray[0])"
}
```
let extensionArray = extensions.map { $0.map { String($0) } } // invalid redeclaration of 'extensionArray'
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.map { String($0) }
var classArray2 = [String]()
for i in classArray {
if i.isUppercase {
classArray2.append(i)
}
}
let classArray3 = classArray2.count
var classArray4 = [String]()
for i in classArray {
if i.isLowercase {
classArray4.append(i)
}
}
let classArray5 = classArray4.count
let classArray6 = classArray3 - classArray5
var classArray7 = [String]()
for i in extensions {
let classArray8 = i.map { String($0) }
var classArray9 = [String]()
for i in classArray8 {
if i.isUppercase {
classArray9.append(i)
}
}
let classArray10 = classArray9.count
var classArray11 = [String]()
for i in classArray8 {
if i.isLowercase {
classArray11.append(i)
}
}
let classArray12 = classArray11.count
let classArray13 = classArray10 - classArray12
if classArray13 == classArray6 {
classArray7.append(i)
}
}
if classArray7.isEmpty {
return "\(className).\(extensions[0])"
} else {
return "\(className).\(classArray7[0])"
}
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.map { String($0) }
var classArray2 = [String]()
for i in classArray {
if i.isUppercase {
classArray2.append(i)
}
}
let classArray3 = classArray2.count
var classArray4 = [String]()
for i in classArray {
if i.isLowercase {
classArray4.append(i)
}
}
let classArray5 = classArray4.count
let classArray6 = classArray3 - classArray5
var classArray7 = [String]()
for i in extensions {
let classArray8 = i.map { String($0) }
var classArray9 = [String]()
for i in classArray8 {
if i.isUppercase {
classArray9.append(i)
}
}
let classArray10 = classArray9.count
var classArray11 = [String]()
for i in classArray8 {
if i.isLowercase {
classArray11.append(i)
}
}
let classArray12 = classArray11.count
let classArray13 = classArray10 - classArray12
if classArray13 == classArray6 {
classArray7.append(i)
}
}
if classArray7.isEmpty {
return "\(className).\(extensions[0])"
} else {
return "\(className).\(classArray7[0])"
}
}
```
if i.isUppercase { // value of type 'String' has no member 'isUppercase'
if i.isLowercase { // value of type 'String' has no member 'isLowercase'
if i.isUppercase { // value of type 'String' has no member 'isUppercase'
if i.isLowercase { // value of type 'String' has no member 'isLowercase'
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0.0
var max_ext = ""
for ext in extensions {
let cap = ext.filter { $0.isUppercase }.count
let sm = ext.filter { $0.isLowercase }.count
let strength = Double(cap - sm)
if strength > max {
max = strength
max_ext = ext
}
}
return className + "." + max_ext
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0.0
var max_ext = ""
for ext in extensions {
let cap = ext.filter { $0.isUppercase }.count
let sm = ext.filter { $0.isLowercase }.count
let strength = Double(cap - sm)
if strength > max {
max = strength
max_ext = ext
}
}
return className + "." + max_ext
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
// your code here
var max = 0
var result = ""
for i in extensions {
var cap = 0
var sm = 0
for j in i {
if j.isUppercase {
cap += 1
} else {
sm += 1
}
}
if cap - sm > max {
max = cap - sm
result = i
}
}
return className + "." + result
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
// your code here
var max = 0
var result = ""
for i in extensions {
var cap = 0
var sm = 0
for j in i {
if j.isUppercase {
cap += 1
} else {
sm += 1
}
}
if cap - sm > max {
max = cap - sm
result = i
}
}
return className + "." + result
}
```
// XCTAssertTrue failed
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.lowercased().characters.split{$0 == "_"}
var classString = String(classArray.joined())
var classArray2 = classString.characters.split{$0 == "."}
var classString2 = String(classArray2.joined())
var classArray3 = classString2.characters.split{$0 == "."}
var classString3 = String(classArray3.joined())
var classArray4 = classString3.characters.split{$0 == "."}
var classString4 = String(classArray4.joined())
var classArray5 = classString4.characters.split{$0 == "."}
var classString5 = String(classArray5.joined())
var classArray6 = classString5.characters.split{$0 == "."}
var classString6 = String(classArray6.joined())
var classArray7 = classString6.characters.split{$0 == "."}
var classString7 = String(classArray7.joined())
var classArray8 = classString7.characters.split{$0 == "."}
var classString8 = String(classArray8.joined())
var classArray9 = classString8.characters.split{$0 == "."}
var classString9 = String(classArray9.joined())
var classArray10 = classString9.characters.split{$0 == "."}
var classString10 = String(classArray10.joined())
var classArray11 = classString10.characters.split{$0 == "."}
var classString11 = String(classArray11.joined())
var classArray12 = classString11.characters.split{$0 == "."}
var classString12 = String(classArray12.joined())
var classArray13 = classString12.characters.split{$0 == "."}
var classString13 = String(classArray13.joined())
var classArray14 = classString13.characters.split{$0 == "."}
var classString14 = String(classArray14.joined())
var classArray15 = classString14.characters.split{$0 == "."}
var classString15 = String(classArray15.joined())
var classArray16 = classString15.characters.split{$0 == "."}
var classString16 = String(classArray16.joined())
var classArray17 = classString16.characters.split{$0 == "."}
var classString17 = String(classArray17.joined())
var classArray18 = classString17.characters.split{$0 == "."}
var classString18 = String(classArray18.joined())
var classArray19 = classString18.characters.split{$0 == "."}
var classString19 = String(classArray19.joined())
var classArray20 = classString19.characters.split{$0 == "."}
var classString20 = String(classArray20.joined())
var classArray21 = classString20.characters.split{$0 == "."}
var classString21 = String(classArray21.joined())
var classArray22 = classString21.characters.split{$0 == "."}
var classString22 = String(classArray22.joined())
var classArray23 = classString22.characters.split{$0 == "."}
var classString23 = String(classArray23.joined())
var classArray24 = classString23.characters.split{$0 == "."}
var classString24 = String(classArray24.joined())
var classArray25 = classString24.characters.split{$0 == "."}
var classString25 = String(classArray25.joined())
var classArray26 = classString25.characters.split{$0 == "."}
var classString26 = String(classArray26.joined())
var classArray27 = classString26.characters.split{$0 == "."}
var classString27 = String(classArray27.joined())
var classArray28 = classString27.characters.split{$0 == "."}
var classString28 = String(classArray28.joined())
XCTAssertTrue(Strongest_Extension(className: "Watashi", extensions: ["tEN", "niNE", "eIGHt8OKe"]) == "Watashi.eIGHt8OKe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Boku123", extensions: ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]) == "Boku123.YEs.WeCaNe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__YESIMHERE", extensions: ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]) == "__YESIMHERE.NuLl__") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "K", extensions: ["Ta", "TAR", "t234An", "cosSo"]) == "K.TAR") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__HAHA", extensions: ["Tab", "123", "781345", "--"]) == "__HAHA.123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "YameRore", extensions: ["HhAas", "okIWILL123", "WorkOut", "Fails", "--"]) == "YameRore.okIWILL123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "finNNalLLly", extensions: ["Die", "NowW", "Wow", "WoW"]) == "finNNalLLly.WoW") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "", extensions: ["Bb", "91245"]) == ".Bb") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Sp", extensions: ["671235", "Bb"]) == "Sp.671235") // cannot find 'Strongest_Extension' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0.0
var maxName = ""
for name in extensions {
let upper = name.filter { $0.isUppercase }
let lower = name.filter { $0.isLowercase }
let value = Double(upper.count) - Double(lower.count)
if value > max {
max = value
maxName = name
}
}
return className + "." + maxName
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0.0
var maxName = ""
for name in extensions {
let upper = name.filter { $0.isUppercase }
let lower = name.filter { $0.isLowercase }
let value = Double(upper.count) - Double(lower.count)
if value > max {
max = value
maxName = name
}
}
return className + "." + maxName
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.split(separator: " ")
var classString = ""
for i in classArray {
classString += i.lowercased()
}
var strongest = ""
var strongestStrength = 0
for i in extensions {
var strength = 0
for j in i {
if j.isUppercase {
strength += 1
} else if j.isLowercase {
strength -= 1
}
}
if strength > strongestStrength {
strongest = i
strongestStrength = strength
}
}
return "\(classString).\(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 {
let classArray = className.split(separator: " ")
var classString = ""
for i in classArray {
classString += i.lowercased()
}
var strongest = ""
var strongestStrength = 0
for i in extensions {
var strength = 0
for j in i {
if j.isUppercase {
strength += 1
} else if j.isLowercase {
strength -= 1
}
}
if strength > strongestStrength {
strongest = i
strongestStrength = strength
}
}
return "\(classString).\(strongest)"
}
```
// XCTAssertTrue failed
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0.0
for extensionName in extensions {
let extensionStrength = Double(extensionName.filter { $0.isUppercase }.count - extensionName.filter { $0.isLowercase }.count)
if extensionStrength > strongestExtensionStrength {
strongestExtension = extensionName
strongestExtensionStrength = extensionStrength
}
}
return "\(className.lowercased()).\(strongestExtension)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0.0
for extensionName in extensions {
let extensionStrength = Double(extensionName.filter { $0.isUppercase }.count - extensionName.filter { $0.isLowercase }.count)
if extensionStrength > strongestExtensionStrength {
strongestExtension = extensionName
strongestExtensionStrength = extensionStrength
}
}
return "\(className.lowercased()).\(strongestExtension)"
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let b = b.lowercased()
let a = a.lowercased()
let bLength = b.count
let aLength = a.count
if bLength > aLength {
return false
}
var bIndex = 0
var aIndex = 0
var bChar = b[b.startIndex]
var aChar = a[a.startIndex]
while bIndex < bLength {
if bChar == aChar {
var bIndex = bIndex
var aIndex = aIndex
var bChar = bChar
var aChar = aChar
while bIndex < bLength {
if bChar == aChar {
bIndex += 1
aIndex += 1
if bIndex == bLength {
return true
}
bChar = b[b.index(b.startIndex, offsetBy: bIndex)]
aChar = a[a.index(a.startIndex, offsetBy: aIndex)]
} else {
break
}
}
}
aIndex += 1
bIndex = 0
bChar = b[b.startIndex]
aChar = a[a.index(a.startIndex, offsetBy: aIndex)]
}
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.lowercased()
let a = a.lowercased()
let bLength = b.count
let aLength = a.count
if bLength > aLength {
return false
}
var bIndex = 0
var aIndex = 0
var bChar = b[b.startIndex]
var aChar = a[a.startIndex]
while bIndex < bLength {
if bChar == aChar {
var bIndex = bIndex
var aIndex = aIndex
var bChar = bChar
var aChar = aChar
while bIndex < bLength {
if bChar == aChar {
bIndex += 1
aIndex += 1
if bIndex == bLength {
return true
}
bChar = b[b.index(b.startIndex, offsetBy: bIndex)]
aChar = a[a.index(a.startIndex, offsetBy: aIndex)]
} else {
break
}
}
}
aIndex += 1
bIndex = 0
bChar = b[b.startIndex]
aChar = a[a.index(a.startIndex, offsetBy: aIndex)]
}
return false
}
```
// Fatal error: String index is out of bounds
```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 b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b.reversed()
var b = b.dropLast()
var b = b.dropFirst()
var b = b
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
```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 a = a.map { String($0) }
let b = b.map { String($0) }
let b = b.map { String($0) }
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b = b
var b
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.map { String($0) }
let b = b.map { String($0) }
let bCount = b.count
let aCount = a.count
let bSet = Set(b)
for i in 0..<aCount - bCount + 1 {
let aSubstring = a[i..<i+bCount]
if bSet.isSubset(of: Set(aSubstring)) {
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 a = a.map { String($0) }
let b = b.map { String($0) }
let bCount = b.count
let aCount = a.count
let bSet = Set(b)
for i in 0..<aCount - bCount + 1 {
let aSubstring = a[i..<i+bCount]
if bSet.isSubset(of: Set(aSubstring)) {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
var a = a
for _ in 1...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
var a = a
for _ in 1...b.count {
if a.contains(b) {
return true
}
b.append(b.removeFirst())
}
return false
}
```
var a = a // variable 'a' was never mutated; consider changing to 'let' constant
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
var a = a
var b_size = b.count
var a_size = a.count
while(b_size < a_size){
b_size = b_size + b.count
}
while(a_size < b_size){
a_size = a_size + a.count
}
for _ in 0...(a_size - b_size){
if(a.contains(b)){
return true
}
let first = b.first!
let rest = String(b.dropFirst())
b = rest + String(first)
}
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
var a = a
var b_size = b.count
var a_size = a.count
while(b_size < a_size){
b_size = b_size + b.count
}
while(a_size < b_size){
a_size = a_size + a.count
}
for _ in 0...(a_size - b_size){
if(a.contains(b)){
return true
}
let first = b.first!
let rest = String(b.dropFirst())
b = rest + String(first)
}
return false
}
```
var a = a // variable 'a' was never mutated; consider changing to 'let' constant
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.map{String($0)}
let b = b.map{String($0)}
let bLen = b.count
let aLen = a.count
for i in 0 ..< aLen {
var j = 0
while j < bLen {
if b[j] != a[(i + j) % aLen] {
break
}
j += 1
}
if j == bLen {
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 a = a.map{String($0)}
let b = b.map{String($0)}
let bLen = b.count
let aLen = a.count
for i in 0 ..< aLen {
var j = 0
while j < bLen {
if b[j] != a[(i + j) % aLen] {
break
}
j += 1
}
if j == bLen {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
var a = a
for _ in 0..<a.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
var a = a
for _ in 0..<a.count {
if a.contains(b) {
return true
}
b.append(b.removeFirst())
}
return false
}
```
var a = a // variable 'a' was never mutated; consider changing to 'let' constant
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
var a = a
let bLength = b.count
let aLength = a.count
while aLength >= bLength {
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
var a = a
let bLength = b.count
let aLength = a.count
while aLength >= bLength {
if a.contains(b) {
return true
}
b.append(b.removeFirst())
}
return false
}
```
var a = a // variable 'a' was never mutated; consider changing to 'let' constant
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
var a = a
while b.count > 0 {
if a.contains(b) {
return true
}
b.insert(b.removeFirst(), at: b.endIndex)
}
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
var a = a
while b.count > 0 {
if a.contains(b) {
return true
}
b.insert(b.removeFirst(), at: b.endIndex)
}
return false
}
```
var a = a // variable 'a' was never mutated; consider changing to 'let' constant
func evenOddCount(num: Int) -> (Int, Int) {
// your code here
}
```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) {
// your code here
}
```
} // missing return in global function expected to return '(Int, Int)'
func evenOddCount(num: Int) -> (Int, Int) {
let numStr = String(num)
var evenCount = 0
var oddCount = 0
for char in numStr {
if char.isWholeNumber {
if Int(String(char))! % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
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) {
let numStr = String(num)
var evenCount = 0
var oddCount = 0
for char in numStr {
if char.isWholeNumber {
if Int(String(char))! % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
```
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 = 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 = num / 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(abs(num))
var even = 0
var odd = 0
for char in str {
if Int(char.description) ?? 0 % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(abs(num))
var even = 0
var odd = 0
for char in str {
if Int(char.description) ?? 0 % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
// TODO: Implement this function
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) {
// TODO: Implement this function
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)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
let numArray = numString.compactMap { Int(String($0)) }
var evenCount = 0
var oddCount = 0
for num in numArray {
if num % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
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) {
let numString = String(num)
let numArray = numString.compactMap { Int(String($0)) }
var evenCount = 0
var oddCount = 0
for num in numArray {
if num % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(abs(num))
var even = 0
var odd = 0
for char in str {
if Int(String(char))! % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(abs(num))
var even = 0
var odd = 0
for char in str {
if Int(String(char))! % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(abs(num))
var evenCount = 0
var oddCount = 0
for char in numString {
let digit = Int(String(char))!
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
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) {
let numString = String(abs(num))
var evenCount = 0
var oddCount = 0
for char in numString {
let digit = Int(String(char))!
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(num)
let arr = Array(str)
var even = 0
var odd = 0
for i in arr {
if Int(String(i))! % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(num)
let arr = Array(str)
var even = 0
var odd = 0
for i in arr {
if Int(String(i))! % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(abs(num))
let arr = str.compactMap { Int(String($0)) }
let even = arr.filter { $0 % 2 == 0 }.count
let odd = arr.filter { $0 % 2 != 0 }.count
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(abs(num))
let arr = str.compactMap { Int(String($0)) }
let even = arr.filter { $0 % 2 == 0 }.count
let odd = arr.filter { $0 % 2 != 0 }.count
return (even, odd)
}
```
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
]
var result = ""
var number = number
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= 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 {
let romanNumerals = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
]
var result = ""
var number = number
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanNumeral = ""
var number = number
for (index, numeral) in numerals.enumerated() {
while number >= numeral {
number -= numeral
romanNumeral += romanNumerals[index]
}
}
return romanNumeral
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanNumeral = ""
var number = number
for (index, numeral) in numerals.enumerated() {
while number >= numeral {
number -= numeral
romanNumeral += romanNumerals[index]
}
}
return romanNumeral
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var roman: String = ""
var num: Int = number
// 1000
while num >= 1000 {
roman += "m"
num -= 1000
}
// 900
if num >= 900 {
roman += "cm"
num -= 900
}
// 500
if num >= 500 {
roman += "d"
num -= 500
}
// 400
if num >= 400 {
roman += "cd"
num -= 400
}
// 100
while num >= 100 {
roman += "c"
num -= 100
}
// 90
if num >= 90 {
roman += "xc"
num -= 90
}
// 50
if num >= 50 {
roman += "l"
num -= 50
}
// 40
if num >= 40 {
roman += "xl"
num -= 40
}
// 10
while num >= 10 {
roman += "x"
num -= 10
}
// 9
if num == 9 {
roman += "ix"
num -= 9
}
// 5
if num >= 5 {
roman += "v"
num -= 5
}
// 4
if num == 4 {
roman += "iv"
num -= 4
}
// 1
while num > 0 {
roman += "i"
num -= 1
}
return roman
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var roman: String = ""
var num: Int = number
// 1000
while num >= 1000 {
roman += "m"
num -= 1000
}
// 900
if num >= 900 {
roman += "cm"
num -= 900
}
// 500
if num >= 500 {
roman += "d"
num -= 500
}
// 400
if num >= 400 {
roman += "cd"
num -= 400
}
// 100
while num >= 100 {
roman += "c"
num -= 100
}
// 90
if num >= 90 {
roman += "xc"
num -= 90
}
// 50
if num >= 50 {
roman += "l"
num -= 50
}
// 40
if num >= 40 {
roman += "xl"
num -= 40
}
// 10
while num >= 10 {
roman += "x"
num -= 10
}
// 9
if num == 9 {
roman += "ix"
num -= 9
}
// 5
if num >= 5 {
roman += "v"
num -= 5
}
// 4
if num == 4 {
roman += "iv"
num -= 4
}
// 1
while num > 0 {
roman += "i"
num -= 1
}
return roman
}
```
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var roman = ""
var num = number
for i in 0..<romanNumerals.count {
while num >= arabicNumerals[i] {
roman += romanNumerals[i]
num -= arabicNumerals[i]
}
}
return roman
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var roman = ""
var num = number
for i in 0..<romanNumerals.count {
while num >= arabicNumerals[i] {
roman += romanNumerals[i]
num -= arabicNumerals[i]
}
}
return roman
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var roman = ""
var num = number
let romanNumerals = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
]
for (int, romanChar) in romanNumerals {
while num >= int {
roman += romanChar
num -= int
}
}
return roman
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var roman = ""
var num = number
let romanNumerals = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
]
for (int, romanChar) in romanNumerals {
while num >= int {
roman += romanChar
num -= int
}
}
return roman
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var number = number
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for (index, number) in numbers.enumerated() {
while number <= number {
result += romanNumerals[index]
number -= number
}
}
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 number = number
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for (index, number) in numbers.enumerated() {
while number <= number {
result += romanNumerals[index]
number -= number
}
}
return result
}
```
number -= number // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i",
]
var result = ""
var number = number
for (value, symbol) in romanNumerals {
while number >= value {
result += symbol
number -= 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 {
let romanNumerals = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i",
]
var result = ""
var number = number
for (value, symbol) in romanNumerals {
while number >= value {
result += symbol
number -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var number = number
let romanNumerals = [
(1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"),
(50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i")
]
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= 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 number = number
let romanNumerals = [
(1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"),
(50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i")
]
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= value
}
}
return result
}
```
func intToMiniRoman(number: Int) -> String {
var roman: String = ""
var num = number
let romanNumerals: [Int: String] = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
]
for (key, value) in romanNumerals {
if num >= key {
let count = num / key
roman += String(repeating: value, count: count)
num -= count * key
}
}
return roman
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var roman: String = ""
var num = number
let romanNumerals: [Int: String] = [
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
]
for (key, value) in romanNumerals {
if num >= key {
let count = num / key
roman += String(repeating: value, count: count)
num -= count * key
}
}
return roman
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var number = number
let romanNumerals = [
(1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"),
(50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i")
]
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= value
}
}
return result.lowercased()
}
```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 number = number
let romanNumerals = [
(1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"),
(50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i")
]
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= value
}
}
return result.lowercased()
}
```
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 a = a * a
let b = b * b
let c = c * c
if a + b == c || a + c == b || b + c == 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 {
let a = a * a
let b = b * b
let c = c * c
if a + b == c || a + c == b || b + c == 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 {
let aSqr = a * a
let bSqr = b * b
let cSqr = c * c
if (aSqr + bSqr == cSqr) {
return true
}
if (aSqr + cSqr == bSqr) {
return true
}
if (bSqr + cSqr == aSqr) {
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 {
let aSqr = a * a
let bSqr = b * b
let cSqr = c * c
if (aSqr + bSqr == cSqr) {
return true
}
if (aSqr + cSqr == bSqr) {
return true
}
if (bSqr + cSqr == aSqr) {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
// TODO: Implement this function
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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
if aSquared + bSquared == cSquared || aSquared + cSquared == bSquared || bSquared + cSquared == aSquared {
return true
}
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 {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
if aSquared + bSquared == cSquared || aSquared + cSquared == bSquared || bSquared + cSquared == aSquared {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
if aSquared + bSquared == cSquared {
return true
} else if bSquared + cSquared == aSquared {
return true
} else if aSquared + cSquared == bSquared {
return true
} else {
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 {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
if aSquared + bSquared == cSquared {
return true
} else if bSquared + cSquared == aSquared {
return true
} else if aSquared + cSquared == bSquared {
return true
} else {
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 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 max = 0
var maxWord = ""
for word in words {
let set = Set(word)
if set.count > max {
max = set.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 {
let set = Set(word)
if set.count > max {
max = set.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let set = Set(word)
if set.count > max {
max = set.count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let set = Set(word)
if set.count > max {
max = set.count
result = word
}
}
return result
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
result = word
}
}
return result
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let set = Set(word)
if set.count > max {
max = set.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 {
let set = Set(word)
if set.count > max {
max = set.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var maxWord = ""
var maxCount = 0
for word in words {
let uniqueChars = Set(word)
if uniqueChars.count > maxCount {
maxCount = uniqueChars.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 maxWord = ""
var maxCount = 0
for word in words {
let uniqueChars = Set(word)
if uniqueChars.count > maxCount {
maxCount = uniqueChars.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
result = word
}
}
return result
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let set = Set(word)
if set.count > max {
max = set.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 {
let set = Set(word)
if set.count > max {
max = set.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var maxCount = 0
var maxWord = ""
for word in words {
let count = word.reduce(into: Set<Character>()){ $0.insert($1) }.count
if count > maxCount {
maxCount = 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 maxCount = 0
var maxWord = ""
for word in words {
let count = word.reduce(into: Set<Character>()){ $0.insert($1) }.count
if count > maxCount {
maxCount = count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let set = Set(word)
if set.count > max {
max = set.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 {
let set = Set(word)
if set.count > max {
max = set.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var maxUnique = 0
var result = ""
for word in words {
var unique = 0
for char in word {
if !result.contains(char) {
unique += 1
}
}
if unique > maxUnique {
maxUnique = unique
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var maxUnique = 0
var result = ""
for word in words {
var unique = 0
for char in word {
if !result.contains(char) {
unique += 1
}
}
if unique > maxUnique {
maxUnique = unique
result = word
}
}
return result
}
```
// 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] {
let total = number + need
let left = remaining - total
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] {
let total = number + need
let left = remaining - total
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrots = remaining - need
if carrots < 0 {
total = number + remaining
carrots = 0
}
return [total, carrots]
}
```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 + need
var carrots = remaining - need
if carrots < 0 {
total = number + remaining
carrots = 0
}
return [total, carrots]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
if remaining >= total {
return [total, remaining - total]
} else {
return [total, 0]
}
}
```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 total = number + need
if remaining >= total {
return [total, remaining - total]
} else {
return [total, 0]
}
}
```
// 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] {
let total = number + need
if total > remaining {
return [total, 0]
} else {
return [total, remaining - total]
}
}
```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 total = number + need
if total > remaining {
return [total, 0]
} else {
return [total, remaining - total]
}
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
if remaining >= total {
return [total, remaining - total]
} else {
return [total, 0]
}
}
```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 total = number + need
if remaining >= total {
return [total, remaining - total]
} else {
return [total, 0]
}
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var carrots = number + need
var remainingCarrots = remaining
if carrots <= remainingCarrots {
remainingCarrots = remainingCarrots - carrots
return [carrots, remainingCarrots]
} else {
carrots = carrots - remainingCarrots
return [carrots, 0]
}
}
```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 carrots = number + need
var remainingCarrots = remaining
if carrots <= remainingCarrots {
remainingCarrots = remainingCarrots - carrots
return [carrots, remainingCarrots]
} else {
carrots = carrots - remainingCarrots
return [carrots, 0]
}
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrots = remaining - need
if carrots < 0 {
total = number + remaining
carrots = 0
}
return [total, carrots]
}
```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 + need
var carrots = remaining - need
if carrots < 0 {
total = number + remaining
carrots = 0
}
return [total, carrots]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
// Write your code here
var total = number + need
var left = remaining - need
if remaining < need {
total = number + remaining
left = 0
}
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] {
// Write your code here
var total = number + need
var left = remaining - need
if remaining < need {
total = number + remaining
left = 0
}
return [total, left]
}
```
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var operands = operands
for operator in operators {
if operator == "-" {
operands[1] = operands[0] - operands[1]
operands.remove(at: 0)
} else if operator == "+" {
operands[1] = operands[0] + operands[1]
operands.remove(at: 0)
} else if operator == "*" {
operands[1] = operands[0] * operands[1]
operands.remove(at: 0)
} else if operator == "//" {
operands[1] = operands[0] / operands[1]
operands.remove(at: 0)
} else if operator == "**" {
operands[1] = pow(operands[0], Double(operands[1]))
operands.remove(at: 0)
}
}
return operands[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 operands = operands
for operator in operators {
if operator == "-" {
operands[1] = operands[0] - operands[1]
operands.remove(at: 0)
} else if operator == "+" {
operands[1] = operands[0] + operands[1]
operands.remove(at: 0)
} else if operator == "*" {
operands[1] = operands[0] * operands[1]
operands.remove(at: 0)
} else if operator == "//" {
operands[1] = operands[0] / operands[1]
operands.remove(at: 0)
} else if operator == "**" {
operands[1] = pow(operands[0], Double(operands[1]))
operands.remove(at: 0)
}
}
return operands[0]
}
```
for operator in operators { // expected Sequence expression for for-each loop
for operator in operators { // expected pattern
for operator in operators { // expected '{' to start the body of for-each loop
if operator == "-" { // operator must be declared as 'prefix', 'postfix', or 'infix'
if operator == "-" { // expected expression, var, or let in 'if' condition
if operator == "-" { // 'operator' may only be declared at file scope
} else if operator == "+" { // 'operator' may only be declared at file scope
} else if operator == "+" { // operator must be declared as 'prefix', 'postfix', or 'infix'
} else if operator == "+" { // expected expression, var, or let in 'if' condition
} else if operator == "*" { // expected expression, var, or let in 'if' condition
} else if operator == "*" { // 'operator' may only be declared at file scope
} else if operator == "*" { // operator must be declared as 'prefix', 'postfix', or 'infix'
} else if operator == "//" { // 'operator' may only be declared at file scope
} else if operator == "//" { // operator must be declared as 'prefix', 'postfix', or 'infix'
} else if operator == "//" { // expected expression, var, or let in 'if' condition
} else if operator == "**" { // operator must be declared as 'prefix', 'postfix', or 'infix'
} else if operator == "**" { // expected expression, var, or let in 'if' condition
} else if operator == "**" { // 'operator' may only be declared at file scope
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var stack = [Int]()
for (index, operator) in operators.enumerated() {
let operand1 = operands[index]
let operand2 = operands[index + 1]
switch operator {
case "+":
stack.append(operand1 + operand2)
case "-":
stack.append(operand1 - operand2)
case "*":
stack.append(operand1 * operand2)
case "//":
stack.append(operand1 / operand2)
case "**":
stack.append(operand1 ** operand2)
default:
break
}
}
return stack.last ?? 0
}
extension Int {
static func **(lhs: Int, rhs: Int) -> Int {
return Int(pow(Double(lhs), Double(rhs)))
}
}
```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 stack = [Int]()
for (index, operator) in operators.enumerated() {
let operand1 = operands[index]
let operand2 = operands[index + 1]
switch operator {
case "+":
stack.append(operand1 + operand2)
case "-":
stack.append(operand1 - operand2)
case "*":
stack.append(operand1 * operand2)
case "//":
stack.append(operand1 / operand2)
case "**":
stack.append(operand1 ** operand2)
default:
break
}
}
return stack.last ?? 0
}
extension Int {
static func **(lhs: Int, rhs: Int) -> Int {
return Int(pow(Double(lhs), Double(rhs)))
}
}
// doAlgebra(operators: ["+", "*", "-"], operands: [2, 3, 4, 5])
```
for (index, operator) in operators.enumerated() { // expected '{' to start the body of for-each loop
for (index, operator) in operators.enumerated() { // expected 'in' after for-each pattern
for (index, operator) in operators.enumerated() { // expected Sequence expression for for-each loop
for (index, operator) in operators.enumerated() { // expected pattern
switch operator { // expected operator name in operator declaration
switch operator { // expected expression in 'switch' statement
static func **(lhs: Int, rhs: Int) -> Int { // operator implementation without matching operator declaration
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = 0
var operand = 0
for (index, operator) in operators.enumerated() {
switch operator {
case "+":
operand += operands[index + 1]
case "-":
operand -= operands[index + 1]
case "*":
operand *= operands[index + 1]
case "//":
operand = operand / operands[index + 1]
case "**":
operand = operand.pow(operands[index + 1])
default:
break
}
}
result = operand + operands[0]
return result
}
extension Int {
func pow(_ power: Int) -> Int {
var result = 1
for _ in 1...power {
result *= self
}
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 = 0
var operand = 0
for (index, operator) in operators.enumerated() {
switch operator {
case "+":
operand += operands[index + 1]
case "-":
operand -= operands[index + 1]
case "*":
operand *= operands[index + 1]
case "//":
operand = operand / operands[index + 1]
case "**":
operand = operand.pow(operands[index + 1])
default:
break
}
}
result = operand + operands[0]
return result
}
extension Int {
func pow(_ power: Int) -> Int {
var result = 1
for _ in 1...power {
result *= self
}
return result
}
}
```
for (index, operator) in operators.enumerated() { // expected pattern
for (index, operator) in operators.enumerated() { // expected '{' to start the body of for-each loop
for (index, operator) in operators.enumerated() { // expected 'in' after for-each pattern
for (index, operator) in operators.enumerated() { // expected Sequence expression for for-each loop
switch operator { // expected operator name in operator declaration
switch operator { // expected expression in 'switch' statement
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var stack = [Int]()
for (index, operator) in operators.enumerated() {
let operand1 = operands[index]
let operand2 = operands[index + 1]
switch operator {
case "+":
stack.append(operand1 + operand2)
case "-":
stack.append(operand1 - operand2)
case "*":
stack.append(operand1 * operand2)
case "//":
stack.append(operand1 / operand2)
case "**":
stack.append(operand1 ** operand2)
default:
fatalError("Invalid operator")
}
}
return stack.last ?? 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 stack = [Int]()
for (index, operator) in operators.enumerated() {
let operand1 = operands[index]
let operand2 = operands[index + 1]
switch operator {
case "+":
stack.append(operand1 + operand2)
case "-":
stack.append(operand1 - operand2)
case "*":
stack.append(operand1 * operand2)
case "//":
stack.append(operand1 / operand2)
case "**":
stack.append(operand1 ** operand2)
default:
fatalError("Invalid operator")
}
}
return stack.last ?? 0
}
```
for (index, operator) in operators.enumerated() { // expected '{' to start the body of for-each loop
for (index, operator) in operators.enumerated() { // expected 'in' after for-each pattern
for (index, operator) in operators.enumerated() { // expected Sequence expression for for-each loop
for (index, operator) in operators.enumerated() { // expected pattern
switch operator { // expected operator name in operator declaration
switch operator { // expected expression in 'switch' statement
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 res = 0
var i = 0
var j = 0
while i < operators.count {
if operators[i] == "+" {
res = operands[j] + operands[j+1]
} else if operators[i] == "-" {
res = operands[j] - operands[j+1]
} else if operators[i] == "*" {
res = operands[j] * operands[j+1]
} else if operators[i] == "/" {
res = operands[j] / operands[j+1]
} else if operators[i] == "**" {
res = pow(operands[j], operands[j+1])
}
j += 2
i += 1
}
return res
}
```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 res = 0
var i = 0
var j = 0
while i < operators.count {
if operators[i] == "+" {
res = operands[j] + operands[j+1]
} else if operators[i] == "-" {
res = operands[j] - operands[j+1]
} else if operators[i] == "*" {
res = operands[j] * operands[j+1]
} else if operators[i] == "/" {
res = operands[j] / operands[j+1]
} else if operators[i] == "**" {
res = pow(operands[j], operands[j+1])
}
j += 2
i += 1
}
return res
}
```
res = pow(operands[j], operands[j+1]) // cannot assign value of type 'Decimal' to type 'Int'
res = pow(operands[j], operands[j+1]) // cannot convert value of type 'Int' to expected argument type 'Decimal'
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var res: Int = operands[0]
for i in 0..<operators.count {
if operators[i] == "+" {
res += operands[i + 1]
} else if operators[i] == "-" {
res -= operands[i + 1]
} else if operators[i] == "*" {
res *= operands[i + 1]
} else if operators[i] == "/" {
res /= operands[i + 1]
} else if operators[i] == "**" {
res = Int(pow(Double(res), Double(operands[i + 1])))
}
}
return res
}
```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 res: Int = operands[0]
for i in 0..<operators.count {
if operators[i] == "+" {
res += operands[i + 1]
} else if operators[i] == "-" {
res -= operands[i + 1]
} else if operators[i] == "*" {
res *= operands[i + 1]
} else if operators[i] == "/" {
res /= operands[i + 1]
} else if operators[i] == "**" {
res = Int(pow(Double(res), Double(operands[i + 1])))
}
}
return res
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var stack = [Int]()
for (index, value) in operators.enumerated() {
if value == "+" {
stack.append(operands[index] + operands[index + 1])
} else if value == "*" {
stack.append(operands[index] * operands[index + 1])
} else if value == "-" {
stack.append(operands[index] - operands[index + 1])
} else if value == "//" {
stack.append(operands[index] / operands[index + 1])
} else if value == "**" {
stack.append(pow(Double(operands[index]), Double(operands[index + 1])))
}
}
return stack.first!
}
```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 stack = [Int]()
for (index, value) in operators.enumerated() {
if value == "+" {
stack.append(operands[index] + operands[index + 1])
} else if value == "*" {
stack.append(operands[index] * operands[index + 1])
} else if value == "-" {
stack.append(operands[index] - operands[index + 1])
} else if value == "//" {
stack.append(operands[index] / operands[index + 1])
} else if value == "**" {
stack.append(pow(Double(operands[index]), Double(operands[index + 1])))
}
}
return stack.first!
}
```
stack.append(pow(Double(operands[index]), Double(operands[index + 1]))) // cannot convert value of type 'Double' to expected argument type 'Int'
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var res = 0
var i = 0
for op in operators {
if op == "*" {
res = operands[i] * operands[i+1]
} else if op == "-" {
res = operands[i] - operands[i+1]
} else if op == "+" {
res = operands[i] + operands[i+1]
} else if op == "//" {
res = operands[i] / operands[i+1]
} else if op == "**" {
res = pow(operands[i], operands[i+1])
}
i += 1
}
return res
}
```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 res = 0
var i = 0
for op in operators {
if op == "*" {
res = operands[i] * operands[i+1]
} else if op == "-" {
res = operands[i] - operands[i+1]
} else if op == "+" {
res = operands[i] + operands[i+1]
} else if op == "//" {
res = operands[i] / operands[i+1]
} else if op == "**" {
res = pow(operands[i], operands[i+1])
}
i += 1
}
return res
}
```
res = pow(operands[i], operands[i+1]) // cannot convert value of type 'Int' to expected argument type 'Decimal'
res = pow(operands[i], operands[i+1]) // cannot assign value of type 'Decimal' to type 'Int'
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result: Int = 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:
print("Invalid operator")
}
}
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: Int = 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:
print("Invalid operator")
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
} else {
return $0
}
}.joined()
}
```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 {
return s.map {
if $0.isLetter {
if $0.isLowercase {
return $0.uppercased()
} else {
return $0.lowercased()
}
} else {
return $0
}
}.joined()
}
```
return $0 // cannot convert value of type 'String.Element' (aka 'Character') to closure result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char >= "A" && char <= "Z" {
result.append(char.lowercaseString)
} else if char >= "a" && char <= "z" {
result.append(char.uppercaseString)
} else {
result.append(char)
}
}
if result == s {
return String(s.characters.reverse())
}
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 >= "A" && char <= "Z" {
result.append(char.lowercaseString)
} else if char >= "a" && char <= "z" {
result.append(char.uppercaseString)
} else {
result.append(char)
}
}
if result == s {
return String(s.characters.reverse())
}
return result
}
```
result.append(char.lowercaseString) // value of type 'Character' has no member 'lowercaseString'
result.append(char.uppercaseString) // value of type 'Character' has no member 'uppercaseString'
return String(s.characters.reverse()) // value of type 'String' has no member 'reverse'
func solve(s: String) -> String {
let sArr = Array(s)
var resultArr = [Character]()
for i in sArr {
if i.isLetter {
if i.isUppercase {
resultArr.append(i.lowercased().first!)
} else {
resultArr.append(i.uppercased().first!)
}
} else {
resultArr.append(i)
}
}
if resultArr.count == 0 {
return s.reversed()
}
return String(resultArr)
}
```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 {
let sArr = Array(s)
var resultArr = [Character]()
for i in sArr {
if i.isLetter {
if i.isUppercase {
resultArr.append(i.lowercased().first!)
} else {
resultArr.append(i.uppercased().first!)
}
} else {
resultArr.append(i)
}
}
if resultArr.count == 0 {
return s.reversed()
}
return String(resultArr)
}
```
return s.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
let letters = s.filter { $0.isLetter }
let nonLetters = s.filter { !$0.isLetter }
var result = ""
if letters.isEmpty {
result = String(s.reversed())
} else {
for letter in letters {
if letter.isUppercase {
result += letter.lowercased()
} else {
result += letter.uppercased()
}
}
}
return result + nonLetters
}
```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 {
let letters = s.filter { $0.isLetter }
let nonLetters = s.filter { !$0.isLetter }
var result = ""
if letters.isEmpty {
result = String(s.reversed())
} else {
for letter in letters {
if letter.isUppercase {
result += letter.lowercased()
} else {
result += letter.uppercased()
}
}
}
return result + nonLetters
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
let arr = s.map{
if $0.isLetter{
return $0.isLowercase ? $0.uppercased() : $0.lowercased()
}else{
return $0
}
}
return arr.reversed().reduce("", +)
}
```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 {
let arr = s.map{
if $0.isLetter{
return $0.isLowercase ? $0.uppercased() : $0.lowercased()
}else{
return $0
}
}
return arr.reversed().reduce("", +)
}
```
return $0 // cannot convert value of type 'String.Element' (aka 'Character') to closure result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char >= "A" && char <= "Z" {
result += String(char).lowercased()
} else if char >= "a" && char <= "z" {
result += String(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 >= "A" && char <= "Z" {
result += String(char).lowercased()
} else if char >= "a" && char <= "z" {
result += String(char).uppercased()
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
} else {
result.append(char)
}
}
if result.isEmpty {
return s.reversed().map { String($0) }.joined()
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
} else {
result.append(char)
}
}
if result.isEmpty {
return s.reversed().map { String($0) }.joined()
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
// your code here
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
} 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 {
// your code here
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result.append(char.uppercased())
} else {
result.append(char.lowercased())
}
} else {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
let s = Array(s)
var result = ""
for i in s {
if i.isLetter {
result += String(i).uppercased()
} else {
result += String(i).lowercased()
}
}
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 {
let s = Array(s)
var result = ""
for i in s {
if i.isLetter {
result += String(i).uppercased()
} else {
result += String(i).lowercased()
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char >= "a" && char <= "z" {
result += String(char.uppercased())
} else if char >= "A" && char <= "Z" {
result += String(char.lowercased())
} 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 >= "a" && char <= "z" {
result += String(char.uppercased())
} else if char >= "A" && char <= "Z" {
result += String(char.lowercased())
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard text.count > 0 else { return nil }
let data = text.data(using: .utf8)
let md5 = data?.md5
return md5?.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.count > 0 else { return nil }
let data = text.data(using: .utf8)
let md5 = data?.md5
return md5?.map { String(format: "%02hhx", $0) }.joined()
}
```
let md5 = data?.md5 // value of type 'Data' has no member 'md5'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = text.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest)
let result = digest.map { String(format: "%02x", $0) }.joined()
return result
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = text.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest)
let result = digest.map { String(format: "%02x", $0) }.joined()
return result
}
```
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest) // 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
CC_MD5(data.withUnsafeBytes { $0 }, 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).
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty { return nil }
let data = text.data(using: .utf8)!
return data.withUnsafeBytes {
let hash = UnsafeRawPointer($0).bindMemory(to: UInt8.self, capacity: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.bytes, CC_LONG(data.count), 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? {
if text.isEmpty { return nil }
let data = text.data(using: .utf8)!
return data.withUnsafeBytes {
let hash = UnsafeRawPointer($0).bindMemory(to: UInt8.self, capacity: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.bytes, CC_LONG(data.count), hash)
return hash.map { String(format: "%02x", $0) }.joined()
}
}
```
let hash = UnsafeRawPointer($0).bindMemory(to: UInt8.self, capacity: Int(CC_MD5_DIGEST_LENGTH)) // cannot convert value of type 'UnsafeRawBufferPointer' to expected argument type 'UnsafeMutableRawPointer'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = text.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.bytes, CC_LONG(data.count), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.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? {
if text.isEmpty {
return nil
}
let data = text.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.bytes, CC_LONG(data.count), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joined()
}
```
CC_MD5(data.bytes, CC_LONG(data.count), &digest) // value of type 'Data' has no member 'bytes'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty { return nil }
let data = text.data(using: .utf8)
let digest = data?.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes, CC_LONG(data!.count), &hash)
return hash
}
let hash = digest!.map { String(format: "%02x", $0) }.joined()
return hash
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty { return nil }
let data = text.data(using: .utf8)
let digest = data?.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes, CC_LONG(data!.count), &hash)
return hash
}
let hash = digest!.map { String(format: "%02x", $0) }.joined()
return hash
}
```
let digest = data?.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> [UInt8] in // 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
CC_MD5(bytes, 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)!
let md5Data = data.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Data in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(pointer.baseAddress, CC_LONG(data.count), &hash)
return Data(hash)
}
return md5Data.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)!
let md5Data = data.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Data in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(pointer.baseAddress, CC_LONG(data.count), &hash)
return Data(hash)
}
return md5Data.map { String(format: "%02hhx", $0) }.joined()
}
```
CC_MD5(pointer.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)
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.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)
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joined()
}
```
_ = 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)
}
let result = digest.reduce("") { $0 + String(format: "%02x", $1) }
return result
}
```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)
}
let result = digest.reduce("") { $0 + String(format: "%02x", $1) }
return result
}
```
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? {
if text.isEmpty { return nil }
let data = text.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0, CC_LONG(data.count), &digest)
}
return (0..<digest.count).reduce("") {
$0 + String(format: "%02x", digest[$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? {
if text.isEmpty { return nil }
let data = text.data(using: .utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_MD5($0, CC_LONG(data.count), &digest)
}
return (0..<digest.count).reduce("") {
$0 + String(format: "%02x", digest[$1])
}
}
```
data.withUnsafeBytes { // 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
_ = CC_MD5($0, 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.count > 0 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, CC_LONG(data.count), &digest)
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.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.count > 0 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, CC_LONG(data.count), &digest)
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joined()
}
```
_ = data.withUnsafeBytes { // 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
CC_MD5($0, 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] = []
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