Metadata
Key | Value |
---|---|
engine | mlx |
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: Write your code here
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: Write your code here
return false
}
```
// XCTAssertTrue failed
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
break
}
}
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
break
}
}
}
return result
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
return numbers.count > 1 && numbers.sorted().enumerated().contains {
let index = $0.offset
let value = $0.element
return index > 0 && index < numbers.count - 1 && abs(value - numbers[index - 1]) <= threshold && abs(value - numbers[index + 1]) <= 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 {
return numbers.count > 1 && numbers.sorted().enumerated().contains {
let index = $0.offset
let value = $0.element
return index > 0 && index < numbers.count - 1 && abs(value - numbers[index - 1]) <= threshold && abs(value - numbers[index + 1]) <= threshold
}
}
```
// XCTAssertTrue failed
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
}
}
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
}
}
}
return result
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
break
}
}
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
break
}
}
}
return result
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
break
}
}
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var result = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) <= threshold {
result = true
break
}
}
}
return result
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var hasCloseElements = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance <= threshold {
hasCloseElements = true
break
}
}
}
return hasCloseElements
}
```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 hasCloseElements = false
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance <= threshold {
hasCloseElements = true
break
}
}
}
return hasCloseElements
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var closed = 0
for char in parenString {
if char == "(" {
open += 1
current += char
} else if char == ")" {
closed += 1
current += char
}
if open == closed {
result.append(current)
current = ""
open = 0
closed = 0
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var closed = 0
for char in parenString {
if char == "(" {
open += 1
current += char
} else if char == ")" {
closed += 1
current += char
}
if open == closed {
result.append(current)
current = ""
open = 0
closed = 0
}
}
return result
}
```
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```
// XCTAssertTrue failed
```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 parenGroups = [String]()
var currentParenGroup = ""
var currentParenGroupIndex = 0
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen = "("
var currentParenGroupClose = ")"
var currentParenGroupOpenIndex = 0
var currentParenGroupCloseIndex = 0
var currentParenGroupOpenCount = 0
var currentParenGroupCloseCount = 0
var currentParenGroupOpen =
XCTAssertTrue(separateParenGroups(parenString: "(()()) ((())) () ((())()())") == ["(()())", "((()))", "()", "((())()())"]) // cannot find 'separateParenGroups' in scope
XCTAssertTrue(separateParenGroups(parenString: "() (()) ((())) (((())))") == ["()", "(())", "((()))", "(((())))"]) // cannot find 'separateParenGroups' in scope
XCTAssertTrue(separateParenGroups(parenString: "(()(())((())))") == ["(()(())((())))"]) // cannot find 'separateParenGroups' in scope
XCTAssertTrue(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]) // cannot find 'separateParenGroups' in scope
func separateParenGroups(parenString: String) -> [String] {
var parenGroups = [String]()
var currentGroup = ""
var openParenCount = 0
var closeParenCount = 0
for char in parenString {
if char == "(" {
openParenCount += 1
} else if char == ")" {
closeParenCount += 1
}
currentGroup.append(char)
if openParenCount == closeParenCount {
parenGroups.append(currentGroup)
currentGroup = ""
openParenCount = 0
closeParenCount = 0
}
}
return parenGroups
}
```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 parenGroups = [String]()
var currentGroup = ""
var openParenCount = 0
var closeParenCount = 0
for char in parenString {
if char == "(" {
openParenCount += 1
} else if char == ")" {
closeParenCount += 1
}
currentGroup.append(char)
if openParenCount == closeParenCount {
parenGroups.append(currentGroup)
currentGroup = ""
openParenCount = 0
closeParenCount = 0
}
}
return parenGroups
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var openParens = 0
for char in parenString {
if char == "(" {
openParens += 1
} else if char == ")" {
openParens -= 1
}
currentString.append(char)
if openParens == 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 openParens = 0
for char in parenString {
if char == "(" {
openParens += 1
} else if char == ")" {
openParens -= 1
}
currentString.append(char)
if openParens == 0 {
result.append(currentString)
currentString = ""
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
// Write your code here
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
// Write your code here
}
```
} // missing return in global function expected to return '[String]'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var openParens = 0
for char in parenString {
if char == "(" {
openParens += 1
currentString += char
} else if char == ")" {
openParens -= 1
currentString += char
} else {
currentString += char
}
if openParens == 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 openParens = 0
for char in parenString {
if char == "(" {
openParens += 1
currentString += char
} else if char == ")" {
openParens -= 1
currentString += char
} else {
currentString += char
}
if openParens == 0 {
result.append(currentString)
currentString = ""
}
}
return result
}
```
currentString += char // cannot convert value of type 'Character' to expected argument type 'String'
currentString += char // cannot convert value of type 'Character' to expected argument type 'String'
currentString += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current.append(char)
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```
// XCTAssertTrue failed
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 - 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 - 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 - 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 belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { $0 + abs($1 - mean) }) / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (result, number) 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 {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (result, number) in
return result + abs(number - mean)
} / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) {
$0 + abs($1 - 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 {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) {
$0 + abs($1 - mean)
} / Double(numbers.count)
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, number) -> [Int] in
var result = result
result.append(number)
if result.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] {
return numbers.reduce([]) { (result, number) -> [Int] in
var result = result
result.append(number)
if result.count > 1 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([Int]()) {
var result = $0
result.append($1)
if $0.count > 0 {
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] {
return numbers.reduce([Int]()) {
var result = $0
result.append($1)
if $0.count > 0 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, element) -> [Int] in
var result = result
result.append(element)
if result.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] {
return numbers.reduce([]) { (result, element) -> [Int] in
var result = result
result.append(element)
if result.count > 1 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, number) in
var result = result
result.append(number)
if result.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] {
return numbers.reduce([]) { (result, number) in
var result = result
result.append(number)
if result.count > 1 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, number) in
var result = result
result.append(number)
if result.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] {
return numbers.reduce([]) { (result, number) in
var result = result
result.append(number)
if result.count > 1 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, number) -> [Int] in
var result = result
result.append(number)
result.append(delimeter)
return result
}
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, number) -> [Int] in
var result = result
result.append(number)
result.append(delimeter)
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, next) -> [Int] in
var result = result
result.append(next)
if result.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] {
return numbers.reduce([]) { (result, next) -> [Int] in
var result = result
result.append(next)
if result.count > 1 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([Int]()) { (result, element) -> [Int] in
var result = result
result.append(element)
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] {
return numbers.reduce([Int]()) { (result, element) -> [Int] in
var result = result
result.append(element)
result.append(delimeter)
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([]) { (result, number) -> [Int] in
var result = result
result.append(number)
if result.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] {
return numbers.reduce([]) { (result, number) -> [Int] in
var result = result
result.append(number)
if result.count > 1 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
return numbers.reduce([Int]()) {
var result = $0
result.append($1)
if $0.count > 0 {
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] {
return numbers.reduce([Int]()) {
var result = $0
result.append($1)
if $0.count > 0 {
result.append(delimeter)
}
return result
}
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var depth = 0
var maxDepth = 0
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
}
result.append(maxDepth)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var depth = 0
var maxDepth = 0
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
}
result.append(maxDepth)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Write your code here
var result = [Int]()
var max = 0
var count = 0
for char in parenString {
if char == "(" {
count += 1
max = max > count? max : count
} else {
count -= 1
}
}
result.append(max)
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] {
// TODO: Write your code here
var result = [Int]()
var max = 0
var count = 0
for char in parenString {
if char == "(" {
count += 1
max = max > count? max : count
} else {
count -= 1
}
}
result.append(max)
return result
}
```
max = max > count? max : count // consecutive statements on a line must be separated by ';'
max = max > count? max : count // cannot use optional chaining on non-optional value of type 'Int'
max = max > count? max : count // cannot assign value of type 'Bool' to type 'Int'
max = max > count? max : count // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
max = max > count? max : count // expected expression
max = max > count? max : count // consecutive statements on a line must be separated by ';'
max = max > count? max : count // variable is unused
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var currentMaxLevel = 0
var currentLevelString = ""
for char in parenString {
if char == "(" {
currentLevel += 1
currentLevelString += "("
if currentLevel > currentMaxLevel {
currentMaxLevel = currentLevel
}
} else if char == ")" {
currentLevel -= 1
currentLevelString += ")"
if currentLevel == 0 {
result.append(currentMaxLevel)
currentMaxLevel = 0
}
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var currentMaxLevel = 0
var currentLevelString = ""
for char in parenString {
if char == "(" {
currentLevel += 1
currentLevelString += "("
if currentLevel > currentMaxLevel {
currentMaxLevel = currentLevel
}
} else if char == ")" {
currentLevel -= 1
currentLevelString += ")"
if currentLevel == 0 {
result.append(currentMaxLevel)
currentMaxLevel = 0
}
}
}
return result
}
```
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
level += 1
maxLevel = max(level, maxLevel)
} else if char == ")" {
level -= 1
}
}
result.append(maxLevel)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
level += 1
maxLevel = max(level, maxLevel)
} else if char == ")" {
level -= 1
}
}
result.append(maxLevel)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
if char == "(" {
depth += 1
parenStack.append(depth)
} else if char == ")" {
depth -= 1
maxDepth = max(maxDepth, depth)
}
}
return parenStack.map { $0 - maxDepth }
}
```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 parenStack = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
if char == "(" {
depth += 1
parenStack.append(depth)
} else if char == ")" {
depth -= 1
maxDepth = max(maxDepth, depth)
}
}
return parenStack.map { $0 - maxDepth }
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(maxLevel, currentLevel)
} else if char == ")" {
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(currentLevel, maxLevel)
} else if char == ")" {
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
maxLevel = max(currentLevel, maxLevel)
} else if char == ")" {
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var parenCount = 0
var maxParenCount = 0
for char in parenString {
if char == "(" {
parenStack.append(parenCount)
parenCount += 1
} else if char == ")" {
parenCount -= 1
maxParenCount = max(maxParenCount, parenStack.removeLast())
}
}
return parenStack.map { maxParenCount - $0 }
}
```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 parenStack = [Int]()
var parenCount = 0
var maxParenCount = 0
for char in parenString {
if char == "(" {
parenStack.append(parenCount)
parenCount += 1
} else if char == ")" {
parenCount -= 1
maxParenCount = max(maxParenCount, parenStack.removeLast())
}
}
return parenStack.map { maxParenCount - $0 }
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Implement this function
return []
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
// TODO: Implement this function
return []
}
```
// XCTAssertTrue failed
func 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) {
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 num in numbers {
sum += num
product *= num
}
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 num in numbers {
sum += num
product *= num
}
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 num in numbers {
sum += num
product *= num
}
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 num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
return (numbers.reduce(0, +), numbers.reduce(1, *))
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var rollingMax = [Int]()
var max = 0
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
rollingMax.append(max)
}
return rollingMax
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var rollingMax = [Int]()
var max = 0
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
rollingMax.append(max)
}
return rollingMax
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func makePalindrome(string: String) -> String {
let palindrome = string.palindrome
let prefix = string.prefix(upTo: palindrome.startIndex)
let postfix = string.suffix(from: palindrome.endIndex)
return postfix + string + postfix.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 palindrome = string.palindrome
let prefix = string.prefix(upTo: palindrome.startIndex)
let postfix = string.suffix(from: palindrome.endIndex)
return postfix + string + postfix.reversed()
}
```
let palindrome = string.palindrome // value of type 'String' has no member 'palindrome'
func makePalindrome(string: String) -> String {
let palindrome = string.palindrome
let prefix = string.prefix(upTo: palindrome.startIndex)
let suffix = string.suffix(from: palindrome.endIndex)
return String(suffix.reversed()) + string + String(prefix.reversed())
}
extension String {
var palindrome: Substring {
var left = startIndex
var right = endIndex
while left < right {
if self[left]!= self[right] {
return self[left...right]
}
left = index(after: left)
right = index(before: right)
}
return self[startIndex..<endIndex]
}
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let palindrome = string.palindrome
let prefix = string.prefix(upTo: palindrome.startIndex)
let suffix = string.suffix(from: palindrome.endIndex)
return String(suffix.reversed()) + string + String(prefix.reversed())
}
extension String {
var palindrome: Substring {
var left = startIndex
var right = endIndex
while left < right {
if self[left]!= self[right] {
return self[left...right]
}
left = index(after: left)
right = index(before: right)
}
return self[startIndex..<endIndex]
}
}
```
if self[left]!= self[right] { // use of '=' in a boolean context, did you mean '=='?
if self[left]!= self[right] { // '=' must have consistent whitespace on both sides
if self[left]!= self[right] { // cannot force unwrap value of non-optional type 'Character'
func makePalindrome(string: String) -> String {
let palindrome = string.prefix(while: { $0 == $0.reversed() })
return string + String(palindrome.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 palindrome = string.prefix(while: { $0 == $0.reversed() })
return string + String(palindrome.reversed())
}
```
let palindrome = string.prefix(while: { $0 == $0.reversed() }) // value of type 'String.Element' (aka 'Character') has no member 'reversed'
func makePalindrome(string: String) -> String {
let palindrome = string.palindrome
let prefix = string.prefix(upTo: palindrome.startIndex)
let suffix = string.suffix(from: palindrome.endIndex)
return suffix + 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 palindrome = string.palindrome
let prefix = string.prefix(upTo: palindrome.startIndex)
let suffix = string.suffix(from: palindrome.endIndex)
return suffix + string + prefix
}
```
let palindrome = string.palindrome // value of type 'String' has no member 'palindrome'
func makePalindrome(string: String) -> String {
let palindrome = string.prefix(string.count / 2)
let prefix = string.prefix(string.count / 2 + 1)
let postfix = string.suffix(string.count / 2 + 1)
return postfix + String(prefix.reversed()) + 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 palindrome = string.prefix(string.count / 2)
let prefix = string.prefix(string.count / 2 + 1)
let postfix = string.suffix(string.count / 2 + 1)
return postfix + String(prefix.reversed()) + palindrome
}
```
return postfix + String(prefix.reversed()) + palindrome // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
return postfix + String(prefix.reversed()) + palindrome // cannot convert value of type 'String' to expected argument type 'String.SubSequence' (aka 'Substring')
return postfix + String(prefix.reversed()) + palindrome // cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type '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 {
var prefix = ""
var postfix = ""
var palindrome = ""
var palindromeLength = 0
var palindromeIndex = 0
var palindromeIndex2 = 0
var palindromeIndex3 = 0
var palindromeIndex4 = 0
var palindromeIndex5 = 0
var palindromeIndex6 = 0
var palindromeIndex7 = 0
var palindromeIndex8 = 0
var palindromeIndex9 = 0
var palindromeIndex10 = 0
var palindromeIndex11 = 0
var palindromeIndex12 = 0
var palindromeIndex13 = 0
var palindromeIndex14 = 0
var palindromeIndex15 = 0
var palindromeIndex16 = 0
var palindromeIndex17 = 0
var palindromeIndex18 = 0
var palindromeIndex19 = 0
var palindromeIndex20 = 0
var palindromeIndex21 = 0
var palindromeIndex22 = 0
var palindromeIndex23 = 0
var palindromeIndex24 = 0
var palindromeIndex25 = 0
var palindromeIndex26 = 0
var palindromeIndex27 = 0
var palindromeIndex28 = 0
var palindromeIndex29 = 0
var palindromeIndex30 = 0
var palindromeIndex31 = 0
var palindromeIndex32 = 0
var palindromeIndex33 = 0
var palindromeIndex34 = 0
var palindromeIndex35 = 0
var palindromeIndex36 = 0
var palindromeIndex37 = 0
var palindromeIndex38 = 0
var palindromeIndex39 = 0
var palindromeIndex40 = 0
var palindromeIndex41 = 0
var palindromeIndex42 = 0
var palindromeIndex43 = 0
var palindromeIndex44 = 0
var palindromeIndex45 = 0
var palindromeIndex46 = 0
var palindromeIndex47 = 0
var palindromeIndex48 = 0
var palindromeIndex49 = 0
var palindromeIndex50 = 0
var palindromeIndex51 = 0
var palindromeIndex52 = 0
var palindromeIndex53 = 0
var palindromeIndex54 = 0
var palindromeIndex55 = 0
var palindromeIndex56 = 0
var palindromeIndex57 = 0
var palindromeIndex58 = 0
var palindromeIndex59 = 0
var palindromeIndex60 = 0
var palindromeIndex61 = 0
var palindromeIndex62 = 0
var palindromeIndex63 = 0
var palindromeIndex64 = 0
var palindromeIndex65 = 0
var palindromeIndex66 = 0
var palindromeIndex67 = 0
var palindromeIndex68 = 0
var palindromeIndex69 = 0
var palindromeIndex70 = 0
var palindromeIndex71 = 0
var palindromeIndex72 = 0
var palindromeIndex73 = 0
var palindromeIndex74 = 0
var palindromeIndex75 = 0
var palindromeIndex76 = 0
var palindromeIndex77 = 0
var palindromeIndex78 = 0
var palindromeIndex79 = 0
var palindromeIndex80 = 0
var palindromeIndex81 = 0
var palindromeIndex82 = 0
var palindromeIndex83 = 0
var palindromeIndex84 = 0
var palindromeIndex85 = 0
var palindromeIndex86 = 0
var palindromeIndex87 = 0
var palindromeIndex88 = 0
var palindromeIndex89 = 0
var palindromeIndex90 = 0
var palindromeIndex91 = 0
var palindromeIndex92 = 0
var palindromeIndex93 = 0
var palindromeIndex94 = 0
var palindromeIndex95 = 0
var palindromeIndex96 = 0
var palindromeIndex97 = 0
var palindromeIndex98 = 0
var palindromeIndex99 = 0
var palindromeIndex100 = 0
var palindromeIndex101 =
XCTAssertTrue(makePalindrome(string: "") == "") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "x") == "x") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "xyz") == "xyzyx") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "xyx") == "xyx") // cannot find 'makePalindrome' in scope
XCTAssertTrue(makePalindrome(string: "jerry") == "jerryrrej") // cannot find 'makePalindrome' in scope
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
var palindrome = ""
var prefix = ""
var postfix = ""
var longestPalindrome = ""
var longestPalindromeLength = 0
var longestPalindromeIndex = 0
var longestPalindromeIndex2 = 0
var longestPalindromeIndex3 = 0
var longestPalindromeIndex4 = 0
var longestPalindromeIndex5 = 0
var longestPalindromeIndex6 = 0
var longestPalindromeIndex7 = 0
var longestPalindromeIndex8 = 0
var longestPalindromeIndex9 = 0
var longestPalindromeIndex10 = 0
var longestPalindromeIndex11 = 0
var longestPalindromeIndex12 = 0
var longestPalindromeIndex13 = 0
var longestPalindromeIndex14 = 0
var longestPalindromeIndex15 = 0
var longestPalindromeIndex16 = 0
var longestPalindromeIndex17 = 0
var longestPalindromeIndex18 = 0
var longestPalindromeIndex19 = 0
var longestPalindromeIndex20 = 0
var longestPalindromeIndex21 = 0
var longestPalindromeIndex22 = 0
var longestPalindromeIndex23 = 0
var longestPalindromeIndex24 = 0
var longestPalindromeIndex25 = 0
var longestPalindromeIndex26 = 0
var longestPalindromeIndex27 = 0
var longestPalindromeIndex28 = 0
var longestPalindromeIndex29 = 0
var longestPalindromeIndex30 = 0
var longestPalindromeIndex31 = 0
var longestPalindromeIndex32 = 0
var longestPalindromeIndex33 = 0
var longestPalindromeIndex34 = 0
var longestPalindromeIndex35 = 0
var longestPalindromeIndex36 = 0
var longestPalindromeIndex37 = 0
var longestPalindromeIndex38 = 0
var longestPalindromeIndex39 = 0
var longestPalindromeIndex40 = 0
var longestPalindromeIndex41 = 0
var longestPalindromeIndex42 = 0
var longestPalindromeIndex43 = 0
var longestPalindromeIndex44 = 0
var longestPalindromeIndex45 = 0
var longestPalindromeIndex46 = 0
var longestPalindromeIndex47 = 0
var longestPalindromeIndex48 = 0
var longestPalindromeIndex49 = 0
var longestPalindromeIndex50 = 0
var longestPalindromeIndex51 = 0
var longestPalindromeIndex52 = 0
var longestPalindromeIndex53 = 0
var longestPalindromeIndex54 = 0
var longestPalindromeIndex55 = 0
var longestPalindromeIndex56 = 0
var longestPalindromeIndex57 = 0
var longestPalindromeIndex58 = 0
var longestPalindromeIndex59 = 0
var longestPalindromeIndex60 = 0
var longestPalindromeIndex61 = 0
var longestPalindromeIndex62 = 0
var longestPalindromeIndex63 = 0
var longestPalindromeIndex64 = 0
var longestPalindromeIndex65 = 0
var longestPalindromeIndex66 = 0
var longestPalindromeIndex67 = 0
var longestPalindromeIndex68 = 0
var longestPalindromeIndex69 = 0
var longestPalindromeIndex70 = 0
var longestPalindromeIndex71 = 0
var longestPalindromeIndex72 = 0
var longestPalindromeIndex73 = 0
var longestPalindromeIndex74 = 0
var longestPalindromeIndex75 = 0
var longestPalindromeIndex76 = 0
var longestPalindromeIndex77 = 0
var longestPalindromeIndex78 = 0
var longestPalindromeIndex79 = 0
var longestPalindromeIndex80 = 0
var longestPalindromeIndex81 = 0
var longestPalindromeIndex82 = 0
var longestPalindromeIndex83 = 0
var longestPalindromeIndex84 = 0
var longestPalindromeIndex85 = 0
var longestPalindromeIndex86 = 0
var longestPalindromeIndex87 = 0
var longestPalindromeIndex88 = 0
var longestPalindromeIndex89 = 0
var longestPalindromeIndex90 = 0
var longestPalindromeIndex91 = 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 palindrome = string.prefix(while: { $0 == $1 })
return string + String(palindrome.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 palindrome = string.prefix(while: { $0 == $1 })
return string + String(palindrome.reversed())
}
```
let palindrome = string.prefix(while: { $0 == $1 }) // contextual closure type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool') expects 1 argument, but 2 were used in closure body
func makePalindrome(string: String) -> String {
guard string.count > 1 else { return string }
let palindrome = string.prefix(string.count / 2)
let reversed = String(palindrome.reversed())
return reversed + string + 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 {
guard string.count > 1 else { return string }
let palindrome = string.prefix(string.count / 2)
let reversed = String(palindrome.reversed())
return reversed + string + reversed
}
```
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
let palindrome = string.prefix(string.count / 2).reversed()
return string + String(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 palindrome = string.prefix(string.count / 2).reversed()
return string + String(palindrome)
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
var result = ""
var a = a
var b = b
while a.count > 0 || b.count > 0 {
let a = a.prefix(1)
let b = b.prefix(1)
if a == b {
result = "0" + result
} else {
result = "1" + result
}
a = String(a.dropFirst())
b = String(b.dropFirst())
}
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 = ""
var a = a
var b = b
while a.count > 0 || b.count > 0 {
let a = a.prefix(1)
let b = b.prefix(1)
if a == b {
result = "0" + result
} else {
result = "1" + result
}
a = String(a.dropFirst())
b = String(b.dropFirst())
}
return result
}
```
a = String(a.dropFirst()) // cannot assign value of type 'String' to type 'String.SubSequence' (aka 'Substring')
a = String(a.dropFirst()) // cannot assign to value: 'a' is a 'let' constant
b = String(b.dropFirst()) // cannot assign value of type 'String' to type 'String.SubSequence' (aka 'Substring')
b = String(b.dropFirst()) // cannot assign to value: 'b' is a 'let' constant
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
result += aChar == bChar? "0" : "1"
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
result += aChar == bChar? "0" : "1"
}
return result
}
```
result += aChar == bChar? "0" : "1" // expected expression
result += aChar == bChar? "0" : "1" // consecutive statements on a line must be separated by ';'
result += aChar == bChar? "0" : "1" // cannot convert value of type 'Bool' to expected argument type 'String'
result += aChar == bChar? "0" : "1" // consecutive statements on a line must be separated by ';'
result += aChar == bChar? "0" : "1" // string literal is unused
result += aChar == bChar? "0" : "1" // cannot use optional chaining on non-optional value of type 'Character'
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
return ""
}
```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 ""
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
var result = ""
var aIndex = a.startIndex
var bIndex = b.startIndex
while aIndex < a.endIndex && bIndex < b.endIndex {
let aChar = a[aIndex]
let bChar = b[bIndex]
if aChar == bChar {
result.append("0")
} else {
result.append("1")
}
aIndex = a.index(after: aIndex)
bIndex = b.index(after: bIndex)
}
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 = ""
var aIndex = a.startIndex
var bIndex = b.startIndex
while aIndex < a.endIndex && bIndex < b.endIndex {
let aChar = a[aIndex]
let bChar = b[bIndex]
if aChar == bChar {
result.append("0")
} else {
result.append("1")
}
aIndex = a.index(after: aIndex)
bIndex = b.index(after: bIndex)
}
return result
}
```
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? {
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? {
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? {
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? {
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? {
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? {
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? {
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 }
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return strings.max(by: { $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(by: { $0.count > $1.count })
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
return strings.max(by: { $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(by: { $0.count > $1.count })
}
```
// 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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Write your code here
}
```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: Write your code here
}
```
} // missing return in global function expected to return 'Int'
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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: Write your code here
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: Write your code here
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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
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
}
```
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
func greatestCommonDivisor(a: Int, b: Int) -> Int {
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 {
return 0
}
```
// XCTAssertTrue failed
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return result
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return result
}
```
result.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
result.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string.prefix(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string.prefix(i)))
}
return prefixes
}
```
// XCTAssertTrue failed
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substring(to: i))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substring(to: i))
}
return prefixes
}
```
prefixes.append(string.substring(to: i)) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i)))
}
return prefixes
}
```
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String.Index' has no member 'advancedBy'
prefixes.append(string.substringToIndex(string.startIndex.advancedBy(i))) // value of type 'String' has no member 'substringToIndex'
func stringSequence(n: Int) -> String {
return (0...n).map(String.init).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 (0...n).map(String.init).joined(separator: " ")
}
```
func stringSequence(n: Int) -> String {
return (0..<n).map(String.init).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 (0..<n).map(String.init).joined(separator: " ")
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return (0..<n).map(String.init).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 (0..<n).map(String.init).joined(separator: " ")
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return (0..<n).map(String.init).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 (0..<n).map(String.init).joined(separator: " ")
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return (0...n).map(String.init).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 (0...n).map(String.init).joined(separator: " ")
}
```
func stringSequence(n: Int) -> String {
return (0..<n).map(String.init).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 (0..<n).map(String.init).joined(separator: " ")
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return (0..<n).map(String.init).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 (0..<n).map(String.init).joined(separator: " ")
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return (0..<n).map(String.init).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 (0..<n).map(String.init).joined(separator: " ")
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
return (0...n).map { String($0) }.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 (0...n).map { String($0) }.joined(separator: " ")
}
```
func stringSequence(n: Int) -> String {
return (0..<n).map { String($0) }.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 (0..<n).map { String($0) }.joined(separator: " ")
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = [Character]()
for character in string.lowercased() {
if!distinctCharacters.contains(character) {
distinctCharacters.append(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 = [Character]()
for character in string.lowercased() {
if!distinctCharacters.contains(character) {
distinctCharacters.append(character)
}
}
return distinctCharacters.count
}
```
if!distinctCharacters.contains(character) { // expected expression, var, or let in 'if' condition
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func countDistinctCharacters(string: String) -> Int {
return string.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).joined().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().components(separatedBy: CharacterSet.alphanumerics.inverted).joined().count
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func countDistinctCharacters(string: String) -> Int {
var characters = Set<Character>()
for character in string.lowercased() {
characters.insert(character)
}
return characters.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 characters = Set<Character>()
for character in string.lowercased() {
characters.insert(character)
}
return characters.count
}
```
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.lowercased()).count
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
currentNote += 1
if currentBeat == 4 {
result.append(currentNote)
currentBeat = 0
currentNote = 0
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
currentNote += 1
if currentBeat == 4 {
result.append(currentNote)
currentBeat = 0
currentNote = 0
}
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```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] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
return musicString.componentsSeparatedByString(" ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```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] {
return musicString.componentsSeparatedByString(" ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```
return musicString.componentsSeparatedByString(" ").map { // value of type 'String' has no member 'componentsSeparatedByString'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var lastBeat = 0
var beat = 0
var lastNote = ""
var note = ""
for char in musicString {
switch char {
case "o":
beat += 1
lastBeat = beat
lastNote = note
note = ""
case "|":
beat += 1
lastBeat = beat
lastNote = note
note = ""
case ".":
beat += 1
lastBeat = beat
lastNote = note
note = ""
default:
note = char
}
}
result.append(lastBeat)
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 lastBeat = 0
var beat = 0
var lastNote = ""
var note = ""
for char in musicString {
switch char {
case "o":
beat += 1
lastBeat = beat
lastNote = note
note = ""
case "|":
beat += 1
lastBeat = beat
lastNote = note
note = ""
case ".":
beat += 1
lastBeat = beat
lastNote = note
note = ""
default:
note = char
}
}
result.append(lastBeat)
return result
}
```
note = char // cannot assign value of type 'Character' to type 'String'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentNote = 0
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentNote += 1
currentBeat += 4
case "o|":
currentNote += 1
currentBeat += 2
case ".|":
currentNote += 1
currentBeat += 1
default:
break
}
result.append(currentBeat)
currentBeat = 0
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentNote = 0
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentNote += 1
currentBeat += 4
case "o|":
currentNote += 1
currentBeat += 2
case ".|":
currentNote += 1
currentBeat += 1
default:
break
}
result.append(currentBeat)
currentBeat = 0
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString.characters {
switch char {
case "o":
currentBeat += 1
case "|" where currentBeat > 0:
currentBeat /= 2
case ".":
currentBeat /= 2
default:
break
}
if currentBeat > 0 {
result.append(currentBeat)
currentBeat = 0
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString.characters {
switch char {
case "o":
currentBeat += 1
case "|" where currentBeat > 0:
currentBeat /= 2
case ".":
currentBeat /= 2
default:
break
}
if currentBeat > 0 {
result.append(currentBeat)
currentBeat = 0
}
}
return result
}
```
var currentNote = 0 // initialization of variable 'currentNote' was never used; consider replacing with assignment to '_' or removing it
for char in musicString.characters { // 'characters' is unavailable: Please use String directly
func parseMusic(musicString: String) -> [Int] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```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] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```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] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```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] {
return musicString.components(separatedBy: " ").map {
switch $0 {
case "o":
return 4
case "o|":
return 2
case ".|":
return 1
default:
return 0
}
}
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var temp = [Int]()
var count = 0
for char in musicString {
if char == "o" {
count += 1
} else if char == "|" {
temp.append(count)
count = 0
}
}
temp.append(count)
for i in 0..<temp.count {
if i % 2 == 0 {
result.append(temp[i])
} else {
result[result.count - 1] += temp[i]
}
}
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 = [Int]()
var count = 0
for char in musicString {
if char == "o" {
count += 1
} else if char == "|" {
temp.append(count)
count = 0
}
}
temp.append(count)
for i in 0..<temp.count {
if i % 2 == 0 {
result.append(temp[i])
} else {
result[result.count - 1] += temp[i]
}
}
return result
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
let range = string.range(of: substring, range: index..<string.count)
if let range = range {
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 = 0
while index < string.count {
let range = string.range(of: substring, range: index..<string.count)
if let range = range {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
let range = string.range(of: substring, range: index..<string.count) // cannot convert value of type 'Int' to expected argument type 'String.Index'
let range = string.range(of: substring, range: index..<string.count) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index!= string.endIndex {
let range = string.range(of: substring, range: index..<string.endIndex)
if let range = range {
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 {
let range = string.range(of: substring, range: index..<string.endIndex)
if let range = range {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
while index!= string.endIndex { // use of '=' in a boolean context, did you mean '=='?
while index!= string.endIndex { // '=' must have consistent whitespace on both sides
while index!= string.endIndex { // cannot force unwrap value of non-optional type 'String.Index'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index!= string.endIndex {
if string[index..<string.endIndex].hasPrefix(substring) {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(after: index)
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index!= string.endIndex {
if string[index..<string.endIndex].hasPrefix(substring) {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(after: index)
}
}
return count
}
```
while index!= string.endIndex { // use of '=' in a boolean context, did you mean '=='?
while index!= string.endIndex { // '=' must have consistent whitespace on both sides
while index!= string.endIndex { // cannot force unwrap value of non-optional type 'String.Index'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
let range = string.range(of: substring, range: index..<string.count)
if let range = range {
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 = 0
while index < string.count {
let range = string.range(of: substring, range: index..<string.count)
if let range = range {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
let range = string.range(of: substring, range: index..<string.count) // cannot convert value of type 'Int' to expected argument type 'String.Index'
let range = string.range(of: substring, range: index..<string.count) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
let range = string.range(of: substring, range: index..<string.endIndex)
if let range = range {
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 {
let range = string.range(of: substring, range: index..<string.endIndex)
if let range = range {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index!= string.endIndex {
if string.hasPrefix(substring) {
count += 1
index = string.index(after: index)
} else {
index = string.index(after: index)
}
}
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.hasPrefix(substring) {
count += 1
index = string.index(after: index)
} else {
index = string.index(after: index)
}
}
return count
}
```
while index!= string.endIndex { // use of '=' in a boolean context, did you mean '=='?
while index!= string.endIndex { // '=' must have consistent whitespace on both sides
while index!= string.endIndex { // cannot force unwrap value of non-optional type 'String.Index'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index...].hasPrefix(substring) {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(index, offsetBy: 1)
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index...].hasPrefix(substring) {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(index, offsetBy: 1)
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index] == substring[substring.startIndex] {
var subIndex = substring.startIndex
var subString = string[index..<string.endIndex]
while subIndex < substring.endIndex {
if subString[subIndex] == substring[subIndex] {
subIndex = subIndex.advanced(by: 1)
} else {
break
}
}
if subIndex == substring.endIndex {
count += 1
index = index.advanced(by: 1)
} else {
index = index.advanced(by: 1)
}
} else {
index = index.advanced(by: 1)
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index] == substring[substring.startIndex] {
var subIndex = substring.startIndex
var subString = string[index..<string.endIndex]
while subIndex < substring.endIndex {
if subString[subIndex] == substring[subIndex] {
subIndex = subIndex.advanced(by: 1)
} else {
break
}
}
if subIndex == substring.endIndex {
count += 1
index = index.advanced(by: 1)
} else {
index = index.advanced(by: 1)
}
} else {
index = index.advanced(by: 1)
}
}
return count
}
```
subIndex = subIndex.advanced(by: 1) // value of type 'String.Index' has no member 'advanced'
index = index.advanced(by: 1) // value of type 'String.Index' has no member 'advanced'
index = index.advanced(by: 1) // value of type 'String.Index' has no member 'advanced'
index = index.advanced(by: 1) // value of type 'String.Index' has no member 'advanced'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index..<string.endIndex].contains(substring) {
count += 1
}
index = string.index(after: index)
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index..<string.endIndex].contains(substring) {
count += 1
}
index = string.index(after: index)
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index..<string.endIndex].hasPrefix(substring) {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(index, offsetBy: 1)
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if string[index..<string.endIndex].hasPrefix(substring) {
count += 1
index = string.index(index, offsetBy: substring.count)
} else {
index = string.index(index, offsetBy: 1)
}
}
return count
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sorted = numbers.components(separatedBy: " ").sorted()
return sorted.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sorted = numbers.components(separatedBy: " ").sorted()
return sorted.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.components(separatedBy: " ").sorted()
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.components(separatedBy: " ").sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
let sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
return numbers.components(separatedBy: " ").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 {
return numbers.components(separatedBy: " ").sorted().joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let arr = numbers.components(separatedBy: " ")
let sortedArr = arr.sorted()
return sortedArr.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 arr = numbers.components(separatedBy: " ")
let sortedArr = arr.sorted()
return sortedArr.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sorted = numbers.components(separatedBy: " ").sorted()
return sorted.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sorted = numbers.components(separatedBy: " ").sorted()
return sorted.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
return numbers.components(separatedBy: " ").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 {
return numbers.components(separatedBy: " ").sorted().joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
return numbers.components(separatedBy: " ").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 {
return numbers.components(separatedBy: " ").sorted().joined(separator: " ")
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair = (0, 0)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair = (0, 0)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
```
minDiffPair = (numbers[i], numbers[j]) // cannot assign value of type '(Double, Double)' to type '(Int, Int)'
return minDiffPair // cannot convert return expression of type '(Int, Int)' to return type '(Double, Double)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair = (0.0, 0.0)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair = (0.0, 0.0)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDistance = Double.greatestFiniteMagnitude
var minDistanceIndex = 0
var minDistanceIndex2 = 0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
minDistanceIndex = i
minDistanceIndex2 = j
}
}
}
return (numbers[minDistanceIndex], numbers[minDistanceIndex2])
}
```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 minDistance = Double.greatestFiniteMagnitude
var minDistanceIndex = 0
var minDistanceIndex2 = 0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
minDistanceIndex = i
minDistanceIndex2 = j
}
}
}
return (numbers[minDistanceIndex], numbers[minDistanceIndex2])
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiff1 = 0.0
var minDiff2 = 0.0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiff1 = numbers[i]
minDiff2 = numbers[j]
}
}
}
return (minDiff1, minDiff2)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiff1 = 0.0
var minDiff2 = 0.0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiff1 = numbers[i]
minDiff2 = numbers[j]
}
}
}
return (minDiff1, minDiff2)
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let midpoint = sortedNumbers.count / 2
let left = sortedNumbers[midpoint - 1]
let right = sortedNumbers[midpoint]
return (left, right)
}
```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 midpoint = sortedNumbers.count / 2
let left = sortedNumbers[midpoint - 1]
let right = sortedNumbers[midpoint]
return (left, right)
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.greatestFiniteMagnitude
var minDiffIndex = 0
var maxDiffIndex = 0
var minDiffIndex2 = 0
var maxDiffIndex2 = 0
var minDiff2 = Double.greatestFiniteMagnitude
var maxDiff2 = Double.greatestFiniteMagnitude
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffIndex = i
maxDiffIndex = j
}
if diff > maxDiff {
maxDiff = diff
minDiffIndex2 = i
maxDiffIndex2 = j
}
}
}
return (numbers[minDiffIndex], numbers[maxDiffIndex])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.greatestFiniteMagnitude
var minDiffIndex = 0
var maxDiffIndex = 0
var minDiffIndex2 = 0
var maxDiffIndex2 = 0
var minDiff2 = Double.greatestFiniteMagnitude
var maxDiff2 = Double.greatestFiniteMagnitude
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffIndex = i
maxDiffIndex = j
}
if diff > maxDiff {
maxDiff = diff
minDiffIndex2 = i
maxDiffIndex2 = j
}
}
}
return (numbers[minDiffIndex], numbers[maxDiffIndex])
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
```
if diff > maxDiff { // cannot find 'maxDiff' in scope
maxDiff = diff // cannot find 'maxDiff' in scope
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.greatestFiniteMagnitude
var minDiffIndex = 0
var maxDiffIndex = 0
var minDiffElement = 0.0
var maxDiffElement = 0.0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffIndex = i
maxDiffIndex = j
}
}
}
minDiffElement = numbers[minDiffIndex]
maxDiffElement = numbers[maxDiffIndex]
return (minDiffElement, maxDiffElement)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.greatestFiniteMagnitude
var minDiffIndex = 0
var maxDiffIndex = 0
var minDiffElement = 0.0
var maxDiffElement = 0.0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffIndex = i
maxDiffIndex = j
}
}
}
minDiffElement = numbers[minDiffIndex]
maxDiffElement = numbers[maxDiffIndex]
return (minDiffElement, maxDiffElement)
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let middle = sortedNumbers.count / 2
let left = sortedNumbers[middle - 1]
let right = sortedNumbers[middle]
return (left, right)
}
```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 middle = sortedNumbers.count / 2
let left = sortedNumbers[middle - 1]
let right = sortedNumbers[middle]
return (left, right)
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDistance = Double.greatestFiniteMagnitude
var minDistanceElements = (0.0, 0.0)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
minDistanceElements = (numbers[i], numbers[j])
}
}
}
return minDistanceElements
}
```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 minDistance = Double.greatestFiniteMagnitude
var minDistanceElements = (0.0, 0.0)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
minDistanceElements = (numbers[i], numbers[j])
}
}
}
return minDistanceElements
}
// 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)
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDistance = Double.infinity
var minDistancePair = (0.0, 0.0)
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
minDistancePair = (numbers[i], numbers[j])
}
}
}
return minDistancePair
}
func firstNonRepeatingCharacter(string: String) -> Character? {
var charCounts = [Character: Int]()
for char in string {
if let count = charCounts[char] {
charCounts[char] = count + 1
} else {
charCounts[char] = 1
}
}
for char in string {
if charCounts[char] == 1 {
return char
}
}
return nil
}
```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 minDistance = Double.infinity
var minDistancePair = (0.0, 0.0)
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < minDistance {
minDistance = distance
minDistancePair = (numbers[i], numbers[j])
}
}
}
return minDistancePair
}
// 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)
// MARK: - 10.10
// Write a function that takes a string as input and returns the first non-repeating character.
// For example, if a string contains all repeating characters, return nil.
// firstNonRepeatingCharacter(string: "abcde") == "e"
// firstNonRepeatingCharacter(string: "abcdeaa") == "e"
// firstNonRepeatingCharacter(string: "abcdea") == "a"
func firstNonRepeatingCharacter(string: String) -> Character? {
var charCounts = [Character: Int]()
for char in string {
if let count = charCounts[char] {
charCounts[char] = count + 1
} else {
charCounts[char] = 1
}
}
for char in string {
if charCounts[char] == 1 {
return char
}
}
return nil
}
// firstNonRepeatingCharacter(string: "abcde") == "e"
// firstNonRepeatingCharacter(string: "abcdeaa") == "e"
// firstNonRepeatingCharacter(string: "abcdea") == "a"
// MARK: - 10.11
// Write a function that takes a string as input and returns the first non-repeating character.
// For example, if a string contains all repeating characters, return nil.
// firstNonRepeatingCharacter(string: "abcde") == "e"
// firstNonRepeatingCharacter(string: "abcdeaa") == "e"
// firstNonRepeatingCharacter(string: "abcdea") == "a"
func firstNonRepeatingCharacter(string: String) -> Character? {
var charCounts = [Character: Int]()
for char in string {
if let count = charCounts[char] {
charCounts[char] = count + 1
} else {
charCounts[char] = 1
}
}
for char in string {
if charCounts[char] == 1 {
return char
}
}
return nil
}
// firstNonRepeatingCharacter(string: "abcde") == "e"
// firstNonRepeatingCharacter(string: "abcdeaa") == "e"
// firstNonRepeatingCharacter(string: "abcdea") == "a"
// MARK: - 10.12
// Write a function that takes a string as input and returns the first non-repeating character.
// For example, if a string contains all repeating characters, return nil.
// firstNonRepeatingCharacter(string: "abcde") == "e"
// firstNonRepeatingCharacter(string: "abcdeaa") == "e"
// firstNonRepeatingCharacter(string: "abcdea") == "a"
func firstNonRepeatingCharacter(string: String) -> Character? {
var charCounts = [Character: Int]()
for char in string {
if let count = charCounts[char] {
charCounts[char] = count + 1
} else {
charCounts[char] = 1
}
}
for char in string {
if charCounts[char] == 1 {
return char
}
}
return nil
}
// firstNonRepeatingCharacter(string: "abcde") == "e"
// firstNonRepeatingCharacter(string: "abcdeaa") == "e"
// firstNonRepeatingCharacter(string: "abcdea") == "a"
// MARK: - 10.13
// Write a function that takes a string as input and returns the first non-repeating character.
// For example
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
return []
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement
return []
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
return []
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: implement this function
return []
}
```
// XCTAssertTrue failed
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] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { (number) -> Double in
return (number - 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 { (number) -> Double in
return (number - min) / (max - min)
}
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
// TODO: Implement this function
return []
}
```
// XCTAssertTrue failed
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = $0 as? Int {
return true
} else {
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = $0 as? Int {
return true
} else {
return false
}
}
}
```
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $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.filter { $0 is Int }.map { $0 as! Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter({ (value) -> Bool in
return value is Int
}).map({ (value) -> Int in
return value as! Int
})
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter({ (value) -> Bool in
return value is Int
}).map({ (value) -> Int in
return value 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.filter { $0 is Int } as! [Int]
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int } as! [Int]
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter({$0 is Int}).map({$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.filter({$0 is Int}).map({$0 as! Int})
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let int = $0 as? Int {
return int
} else {
return nil
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let int = $0 as? Int {
return int
} else {
return nil
}
}
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $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.filter { $0 is Int }.map { $0 as! Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $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.filter { $0 is Int }.map { $0 as! Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $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.filter { $0 is Int }.map { $0 as! Int }
}
```
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func first(string: String) -> Character? {
return string.isEmpty? nil : string.first
}
func last(string: String) -> Character? {
return string.isEmpty? nil : string.last
}
func charAt(string: String, index: Int) -> Character? {
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)]
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
// Return the first character of given string
// first(string: "") == nil
// first(string: "abc") == "a"
func first(string: String) -> Character? {
return string.isEmpty? nil : string.first
}
// Return the last character of given string
// last(string: "") == nil
// last(string: "abc") == "c"
func last(string: String) -> Character? {
return string.isEmpty? nil : string.last
}
// Return the character at given index of given string
// charAt(string: "", index: 0) == nil
// charAt(string: "abc", index: 0) == "a"
// charAt(string: "abc", index: 1) == "b"
// charAt(string: "abc", index: 2) == "c"
// charAt(string: "abc", index: 3) == nil
func charAt(string: String, index: Int) -> Character? {
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)]
}
// Return the character at given index of given string
// charAt(string: "", index: 0) == nil
// charAt(string: "abc", index: 0) == "a"
// charAt(string: "abc", index: 1) == "b"
// charAt(string: "abc", index: 2) == "c"
// charAt(string: "abc", index: 3) == nil
func charAt(string: String, index: Int) -> Character? {
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)]
}
// Return the character at given index of given string
// charAt(string: "", index: 0) == nil
// charAt(string: "abc", index: 0) == "a"
// charAt(string: "abc", index: 1) == "b"
// charAt(string: "abc", index: 2) == "c"
// charAt(string: "abc", index: 3) == nil
func charAt(string: String, index: Int) -> Character? {
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)]
}
// Return the character at given index of given string
// charAt(string: "", index: 0) == nil
// charAt(string: "abc", index: 0) == "a"
// charAt(string: "abc", index: 1) == "b"
// charAt(string: "abc", index: 2) == "c"
// charAt(string: "abc", index: 3) == nil
func charAt(string: String, index: Int) -> Character? {
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)]
}
// Return the character at given index of given string
// charAt(string: "", index: 0) == nil
// charAt(string: "abc", index: 0) == "a"
// charAt(string: "abc", index: 1) == "b"
// charAt(string: "abc", index: 2) == "c"
// charAt(string: "abc", index: 3) == nil
func charAt(string: String, index: Int) -> Character? {
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)]
}
// Return the character at given index of given string
// charAt(string: "", index: 0) == nil
// charAt(string: "abc", index: 0) == "a"
// charAt(string: "abc", index: 1) == "b"
// charAt(string: "abc", index: 2) == "c"
// charAt(string: "abc", index: 3) == nil
func charAt(string: String, index: Int) -> Character
return string.isEmpty? nil : string.first // type of expression is ambiguous without a type annotation
return string.isEmpty? nil : string.first // expected expression
return string.isEmpty? nil : string.first // 'nil' requires a contextual type
return string.isEmpty? nil : string.first // consecutive statements on a line must be separated by ';'
return string.isEmpty? nil : string.first // consecutive statements on a line must be separated by ';'
return string.isEmpty? nil : string.last // expected expression
return string.isEmpty? nil : string.last // consecutive statements on a line must be separated by ';'
return string.isEmpty? nil : string.last // 'nil' requires a contextual type
return string.isEmpty? nil : string.last // type of expression is ambiguous without a type annotation
return string.isEmpty? nil : string.last // consecutive statements on a line must be separated by ';'
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // 'nil' requires a contextual type
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // consecutive statements on a line must be separated by ';'
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // cannot use optional chaining on non-optional value of type 'Int'
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // cannot convert return expression of type 'Bool' to return type 'Character?'
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // expected expression
return string.isEmpty || index < 0 || index >= string.count? nil : string[string.index(string.startIndex, offsetBy: index)] // consecutive statements on a line must be separated by ';'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
```
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
```
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
```
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
```
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
```
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = n
var largestDivisor = 1
while divisor > 1 {
if n % divisor == 0 {
largestDivisor = divisor
}
divisor -= 1
}
return largestDivisor
}
```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
var largestDivisor = 1
while divisor > 1 {
if n % divisor == 0 {
largestDivisor = divisor
}
divisor -= 1
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```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 largestDivisor = 1
for i in 2...n {
if n % i == 0 {
largestDivisor = i
}
}
return largestDivisor
}
```
// XCTAssertTrue failed
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
if number > 1 {
factors.append(number)
}
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 factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var factor = 2
while n > 1 {
if n % factor == 0 {
factors.append(factor)
n /= factor
} else {
factor += 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 factor = 2
while n > 1 {
if n % factor == 0 {
factors.append(factor)
n /= factor
} else {
factor += 1
}
}
return factors
}
```
n /= factor // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i * i <= n {
if n % i == 0 {
result.append(i)
result.append(n / i)
n = n / i
} else {
i += 1
}
}
if n > 1 {
result.append(n)
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i * i <= n {
if n % i == 0 {
result.append(i)
result.append(n / i)
n = n / i
} else {
i += 1
}
}
if n > 1 {
result.append(n)
}
return result
}
```
n = n / i // cannot assign to value: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i * i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i * i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i * i <= n {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i * i <= n {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while number > 1 {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 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 factor = 2
while number > 1 {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
if number > 1 {
factors.append(number)
}
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 factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
if number > 1 {
factors.append(number)
}
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 factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while number > 1 {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 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 factor = 2
while number > 1 {
if number % factor == 0 {
factors.append(factor)
number /= factor
} else {
factor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i * i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i * i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
if number > 1 {
factors.append(number)
}
return factors
}
```
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if!result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if!result.contains(number) {
result.append(number)
}
}
return result
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if!result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if!result.contains(number) {
result.append(number)
}
}
return result
}
```
if!result.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.contains(number) {
continue
}
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) {
continue
}
result.append(number)
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for number in numbers {
if dict[number] == nil {
dict[number] = 1
result.append(number)
} else {
dict[number]! += 1
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for number in numbers {
if dict[number] == nil {
dict[number] = 1
result.append(number)
} else {
dict[number]! += 1
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for number in numbers {
if seen[number] == nil {
result.append(number)
seen[number] = true
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for number in numbers {
if seen[number] == nil {
result.append(number)
seen[number] = true
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if seen.contains(number) {
continue
}
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) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var temp = [Int: Int]()
for i in numbers {
if temp[i] == nil {
temp[i] = 1
result.append(i)
}
}
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 temp = [Int: Int]()
for i in numbers {
if temp[i] == nil {
temp[i] = 1
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if seen.contains(number) {
continue
}
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) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Bool]()
for num in numbers {
if dict[num] == nil {
dict[num] = true
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]()
var dict = [Int: Bool]()
for num in numbers {
if dict[num] == nil {
dict[num] = true
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) {
continue
}
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) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
```
// XCTAssertTrue failed
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return String($0.uppercased())
} else {
return String($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 String($0.uppercased())
} else {
return String($0.lowercased())
}
}
.joined()
}
```
func flipCase(string: String) -> String {
return string.map { $0.isUppercase? $0.lowercased() : $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 { $0.isUppercase? $0.lowercased() : $0.uppercased() }
.joined()
}
```
return string.map { $0.isUppercase? $0.lowercased() : $0.uppercased() } // consecutive statements on a line must be separated by ';'
return string.map { $0.isUppercase? $0.lowercased() : $0.uppercased() } // consecutive statements on a line must be separated by ';'
return string.map { $0.isUppercase? $0.lowercased() : $0.uppercased() } // expected expression
return string.map { $0.isUppercase? $0.lowercased() : $0.uppercased() } // cannot use optional chaining on non-optional value of type 'Bool'
func flipCase(string: String) -> String {
return string.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $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.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $0.lowercased() }
.joined()
}
```
return string.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $0.lowercased() } // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String?'
return string.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $0.lowercased() } // cannot use optional chaining on non-optional value of type 'String'
return string.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $0.lowercased() } // consecutive statements on a line must be separated by ';'
return string.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $0.lowercased() } // expected expression
return string.lowercased().map { $0 == $0.lowercased()? $0.uppercased() : $0.lowercased() } // consecutive statements on a line must be separated by ';'
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += char.uppercased()
} else {
result += char.lowercased()
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += char.uppercased()
} else {
result += char.lowercased()
}
}
return result
}
```
func flipCase(string: String) -> String {
return string.lowercased().map {
if $0.isUppercase {
return String($0.lowercased())
} else {
return String($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.lowercased().map {
if $0.isUppercase {
return String($0.lowercased())
} else {
return String($0.uppercased())
}
}.joined()
}
```
// XCTAssertTrue failed
func flipCase(string: String) -> String {
return string.map {
if $0.isUppercase {
return String($0.lowercased())
} else {
return String($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 String($0.lowercased())
} else {
return String($0.uppercased())
}
}
.joined()
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return String($0).uppercased()
} else {
return String($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 String($0).uppercased()
} else {
return String($0).lowercased()
}
}
.joined()
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return String($0.uppercased())
} else {
return String($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 String($0.uppercased())
} else {
return String($0.lowercased())
}
}.joined()
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return String($0.uppercased())
} else {
return String($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 String($0.uppercased())
} else {
return String($0.lowercased())
}
}.joined()
}
```
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return String($0.uppercased())
} else {
return String($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 String($0.uppercased())
} else {
return String($0.lowercased())
}
}
.joined()
}
```
func concatenate(strings: [String]) -> String {
return strings.reduce("", { $0 + $1 })
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", { $0 + $1 })
}
```
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func concatenate(integers: [Int]) -> Int {
return integers.reduce(0, +)
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Concatenate array of integers into a single integer
// concatenate(integers: []) == 0
// concatenate(integers: [1, 2, 3]) == 6
func concatenate(integers: [Int]) -> Int {
return integers.reduce(0, +)
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
```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
}
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
```
func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
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 {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
```
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
func concatenate(strings: [String]) -> String {
return strings.reduce("", { $0 + $1 })
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", { $0 + $1 })
}
```
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
```
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func concatenate(integers: [Int]) -> Int {
return integers.reduce(0, +)
}
func concatenate(floats: [Float]) -> Float {
return floats.reduce(0.0, +)
}
func concatenate(doubles: [Double]) -> Double {
return doubles.reduce(0.0, +)
}
func concatenate(characters: [Character]) -> String {
return String(characters)
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Concatenate array of integers into a single integer
// concatenate(integers: []) == 0
// concatenate(integers: [1, 2, 3]) == 6
func concatenate(integers: [Int]) -> Int {
return integers.reduce(0, +)
}
// Concatenate array of floats into a single float
// concatenate(floats: []) == 0.0
// concatenate(floats: [1.0, 2.0, 3.0]) == 6.0
func concatenate(floats: [Float]) -> Float {
return floats.reduce(0.0, +)
}
// Concatenate array of doubles into a single double
// concatenate(doubles: []) == 0.0
// concatenate(doubles: [1.0, 2.0, 3.0]) == 6.0
func concatenate(doubles: [Double]) -> Double {
return doubles.reduce(0.0, +)
}
// Concatenate array of characters into a single character
// concatenate(characters: []) == ""
// concatenate(characters: ["a", "b", "c"]) == "abc"
func concatenate(characters: [Character]) -> String {
return String(characters)
}
```
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 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 }
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter({ $0 > 0 })
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter({ $0 > 0 })
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter({$0 > 0})
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
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: Write your code here
return true
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
}
```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: Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
return false
}
```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: Write your code here
return false
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
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: Write your code here
return true
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// TODO: Implement this function
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 this function
return true
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
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: Write your code here
return true
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
return false
}
```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: Write your code here
return false
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// TODO: Write your code here
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: Write your code here
return true
}
```
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
// Write your code here
return false
}
```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 {
// Write your code here
return false
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.index(after: i)
let k = l.index(after: j)
let v = l[i]
l[i] = l[j]
l[j] = l[k]
l[k] = v
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.index(after: i)
let k = l.index(after: j)
let v = l[i]
l[i] = l[j]
l[j] = l[k]
l[k] = v
i += 1
}
return l
}
```
// Fatal error: Index out of range
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = i + 1
while j < l.count {
if l[j] % 3 == 0 {
break
}
j += 1
}
if j == l.count {
break
}
l[i] = l[j]
l[j] = l[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 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 i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = i + 1
while j < l.count {
if l[j] % 3 == 0 {
break
}
j += 1
}
if j == l.count {
break
}
l[i] = l[j]
l[j] = l[i]
i += 1
}
return l
}
```
j += 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.count - 1
while j > i {
if l[j] % 3 == 0 {
l.swapAt(i, j)
break
}
j -= 1
}
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.count - 1
while j > i {
if l[j] % 3 == 0 {
l.swapAt(i, j)
break
}
j -= 1
}
i += 1
}
return l
}
```
j -= 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
} else {
let j = l.count - 1
l[i] = l[j]
l[j] = 0
l.removeLast()
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
} else {
let j = l.count - 1
l[i] = l[j]
l[j] = 0
l.removeLast()
i += 1
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
return l.enumerated().map { (index, value) in
if index % 3 == 0 {
return value
} else {
return l.sorted()[index]
}
}
}
```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.enumerated().map { (index, value) in
if index % 3 == 0 {
return value
} else {
return l.sorted()[index]
}
}
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
} else {
let j = l.count - 1
let temp = l[j]
l[j] = l[i]
l[i] = temp
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
} else {
let j = l.count - 1
let temp = l[j]
l[j] = l[i]
l[i] = temp
i += 1
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.index(after: i)
while j < l.count {
if l[j] % 3 == 0 {
l.swapAt(i, j)
i += 1
break
}
j += 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
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.index(after: i)
while j < l.count {
if l[j] % 3 == 0 {
l.swapAt(i, j)
i += 1
break
}
j += 1
}
}
return l
}
```
j += 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.count - 1
while j > i {
if l[j] % 3 == 0 {
l.swapAt(i, j)
break
}
j -= 1
}
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
i += 1
continue
}
let j = l.count - 1
while j > i {
if l[j] % 3 == 0 {
l.swapAt(i, j)
break
}
j -= 1
}
i += 1
}
return l
}
```
j -= 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
func sortThird(l: [Int]) -> [Int] {
var l = l
let sorted = l.sorted()
var i = 0
var j = 0
while i < l.count {
if l[i] % 3 == 0 {
l[i] = sorted[j]
j += 1
}
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
let sorted = l.sorted()
var i = 0
var j = 0
while i < l.count {
if l[i] % 3 == 0 {
l[i] = sorted[j]
j += 1
}
i += 1
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var third = l.filter({ $0 % 3 == 0 })
third.sort()
var thirdIndex = 0
for i in 0..<l.count {
if l[i] % 3 == 0 {
l[i] = third[thirdIndex]
thirdIndex += 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
var third = l.filter({ $0 % 3 == 0 })
third.sort()
var thirdIndex = 0
for i in 0..<l.count {
if l[i] % 3 == 0 {
l[i] = third[thirdIndex]
thirdIndex += 1
}
}
return l
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for i in l {
if!seen[i] {
result.append(i)
seen[i] = true
}
}
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]()
var seen = [Int: Bool]()
for i in l {
if!seen[i] {
result.append(i)
seen[i] = true
}
}
return result
}
```
if!seen[i] { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for i in l {
if!seen[i] {
result.append(i)
seen[i] = true
}
}
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]()
var seen = [Int: Bool]()
for i in l {
if!seen[i] {
result.append(i)
seen[i] = true
}
}
return result
}
```
if!seen[i] { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for i in l {
if!seen.contains(i) {
result.append(i)
seen.insert(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]()
var seen = Set<Int>()
for i in l {
if!seen.contains(i) {
result.append(i)
seen.insert(i)
}
}
return result
}
```
if!seen.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for i in l {
if!seen[i] {
result.append(i)
seen[i] = true
}
}
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]()
var seen = [Int: Bool]()
for i in l {
if!seen[i] {
result.append(i)
seen[i] = true
}
}
return result
}
```
if!seen[i] { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for i in l {
if seen[i] == nil {
result.append(i)
seen[i] = true
}
}
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]()
var seen = [Int: Bool]()
for i in l {
if seen[i] == nil {
result.append(i)
seen[i] = true
}
}
return result
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for e in l {
if seen[e] == nil {
result.append(e)
seen[e] = true
}
}
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]()
var seen = [Int: Bool]()
for e in l {
if seen[e] == nil {
result.append(e)
seen[e] = true
}
}
return result
}
```
// XCTAssertTrue failed
func maxElement(l: [Int]) -> Int {
return l.maxElement()?? 0
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.maxElement()?? 0
}
```
return l.maxElement()?? 0 // integer literal is unused
return l.maxElement()?? 0 // cannot convert return expression of type 'Optional<_>' to return type 'Int'
return l.maxElement()?? 0 // consecutive statements on a line must be separated by ';'
return l.maxElement()?? 0 // value of type '[Int]' has no member 'maxElement'
func maxElement(l: [Int]) -> Int {
return l.maxElement()!
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.maxElement()!
}
```
return l.maxElement()! // value of type '[Int]' has no member 'maxElement'
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 {
return l.reduce(0, max)
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.reduce(0, max)
}
```
func maxElement(l: [Int]) -> Int {
return l.max()?? 0
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.max()?? 0
}
```
return l.max()?? 0 // integer literal is unused
return l.max()?? 0 // cannot use optional chaining on non-optional value of type 'Int'
return l.max()?? 0 // consecutive statements on a line must be separated by ';'
func maxElement(l: [Int]) -> Int {
return l.maxElement()?? 0
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.maxElement()?? 0
}
```
return l.maxElement()?? 0 // integer literal is unused
return l.maxElement()?? 0 // cannot convert return expression of type 'Optional<_>' to return type 'Int'
return l.maxElement()?? 0 // consecutive statements on a line must be separated by ';'
return l.maxElement()?? 0 // value of type '[Int]' has no member 'maxElement'
func maxElement(l: [Int]) -> Int {
return l.reduce(0, max)
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.reduce(0, max)
}
```
func maxElement(l: [Int]) -> Int {
return l.reduce(0, max)
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.reduce(0, 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 fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (i, v) in
return i % 2 == 0? v : v.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] {
return l.enumerated().map { (i, v) in
return i % 2 == 0? v : v.sorted()
}
}
```
return i % 2 == 0? v : v.sorted() // expected expression
return i % 2 == 0? v : v.sorted() // consecutive statements on a line must be separated by ';'
return i % 2 == 0? v : v.sorted() // cannot convert value of type 'Bool' to closure result type 'Int'
return i % 2 == 0? v : v.sorted() // consecutive statements on a line must be separated by ';'
return i % 2 == 0? v : v.sorted() // cannot use optional chaining on non-optional value of type 'Int'
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map {
if $0.offset % 2 == 0 {
return $0.element
} else {
return $0.element.sorted()
}
}.flatMap { $0 }
}
```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] {
return l.enumerated().map {
if $0.offset % 2 == 0 {
return $0.element
} else {
return $0.element.sorted()
}
}.flatMap { $0 }
}
```
return $0.element // cannot convert value of type 'Int' to closure result type 'String'
}.flatMap { $0 } // cannot convert return expression of type '[String]' to return type '[Int]'
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (i, v) in
return i % 2 == 0? v : l[i / 2]
}.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] {
return l.enumerated().map { (i, v) in
return i % 2 == 0? v : l[i / 2]
}.sorted()
}
```
return i % 2 == 0? v : l[i / 2] // cannot use optional chaining on non-optional value of type 'Int'
return i % 2 == 0? v : l[i / 2] // consecutive statements on a line must be separated by ';'
return i % 2 == 0? v : l[i / 2] // consecutive statements on a line must be separated by ';'
return i % 2 == 0? v : l[i / 2] // cannot convert value of type 'Bool' to closure result type 'Int'
return i % 2 == 0? v : l[i / 2] // expected expression
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l.sorted()[index]
}
}
}
```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] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l.sorted()[index]
}
}
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l.sorted()[index]
}
}
}
```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] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l.sorted()[index]
}
}
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l[index - 1]
}
}.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] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l[index - 1]
}
}.sorted()
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().sorted { $0.offset % 2 == 0 && $0.element < $1.element }.map { $0.element }
}
```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] {
return l.enumerated().sorted { $0.offset % 2 == 0 && $0.element < $1.element }.map { $0.element }
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (i, v) in
if i % 2 == 0 {
return v
} else {
return v.sorted()
}
}.flatMap { $0 }
}
```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] {
return l.enumerated().map { (i, v) in
if i % 2 == 0 {
return v
} else {
return v.sorted()
}
}.flatMap { $0 }
}
```
return v // cannot convert value of type 'Int' to closure result type 'String'
}.flatMap { $0 } // cannot convert return expression of type '[String]' to return type '[Int]'
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (i, v) in
if i % 2 == 0 {
return v
} else {
return l.sorted()[i]
}
}
}
```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] {
return l.enumerated().map { (i, v) in
if i % 2 == 0 {
return v
} else {
return l.sorted()[i]
}
}
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l[index - 1]
}
}.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] {
return l.enumerated().map { (index, value) in
if index % 2 == 0 {
return value
} else {
return l[index - 1]
}
}.sorted()
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
}
i = j
j = k
}
return fib[n - 1]
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if n == 2 { return true }
if n % 2 == 0 { return false }
for i in 3...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 = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
}
i = j
j = k
}
return fib[n - 1]
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if n == 2 { return true }
if n % 2 == 0 { return false }
for i in 3...Int(sqrt(Double(n))) {
if n % i == 0 { return false }
}
return true
}
```
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
}
i = j
j = k
}
return fib[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 = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
}
i = j
j = k
}
return fib[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
}
```
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib.count < n {
fib.append(fib[i - 2] + fib[i - 1])
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 {
fib.append(fib[i - 2] + fib[i - 1])
i += 1
}
return fib[n - 1]
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 0..<n {
c = a + b
a = b
b = c
}
return c
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 0
var i = 3
while i < n {
c = a + b
a = b
b = c
i += 1
}
return c
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 0
var i = 3
while i < n {
c = a + b
a = b
b = c
i += 1
}
return c
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 0
var i = 3
while i < n {
c = a + b
a = b
b = c
i += 1
}
return c
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 0
var i = 3
while i < n {
c = a + b
a = b
b = c
i += 1
}
return c
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
i += 1
}
j = i + j
}
return fib[n - 1]
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if n == 2 { return true }
if n % 2 == 0 { return false }
for i in 3..<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 = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
i += 1
}
j = i + j
}
return fib[n - 1]
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if n == 2 { return true }
if n % 2 == 0 { return false }
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
func primeFib(n: Int) -> Int {
var fib = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
i += 1
}
j = i + j
}
return fib[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 = [Int]()
var i = 0
var j = 1
var k = 0
while i < n {
k = i + j
if isPrime(k) {
fib.append(k)
i += 1
}
j = i + j
}
return fib[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
}
```
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 {
var result = false
var dict = [Int: Int]()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if dict[sum] == nil {
dict[sum] = 1
} else {
dict[sum] = dict[sum]! + 1
}
}
}
for i in 0..<l.count {
let sum = l[i] * -1
if dict[sum]!= nil {
if dict[sum]! > 1 {
result = true
}
}
}
return result
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var result = false
var dict = [Int: Int]()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if dict[sum] == nil {
dict[sum] = 1
} else {
dict[sum] = dict[sum]! + 1
}
}
}
for i in 0..<l.count {
let sum = l[i] * -1
if dict[sum]!= nil {
if dict[sum]! > 1 {
result = true
}
}
}
return result
}
```
if dict[sum]!= nil { // use of '=' in a boolean context, did you mean '=='?
if dict[sum]!= nil { // '=' must have consistent whitespace on both sides
if dict[sum]!= nil { // 'nil' cannot be assigned to type 'Int'
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// your code here
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// your code here
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var result = false
var dict = [Int: Int]()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if dict[sum]!= nil {
result = true
}
dict[sum] = 1
}
}
return result
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var result = false
var dict = [Int: Int]()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if dict[sum]!= nil {
result = true
}
dict[sum] = 1
}
}
return result
}
```
if dict[sum]!= nil { // 'nil' cannot be assigned to type 'Int'
if dict[sum]!= nil { // use of '=' in a boolean context, did you mean '=='?
if dict[sum]!= nil { // '=' must have consistent whitespace on both sides
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 {
// 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 {
// 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 {
var dict = [Int: Int]()
for i in l {
if let j = dict[i] {
dict[i] = j + 1
} else {
dict[i] = 1
}
}
for i in l {
if let j = dict[i] {
if j > 1 {
return true
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if let j = dict[i] {
dict[i] = j + 1
} else {
dict[i] = 1
}
}
for i in l {
if let j = dict[i] {
if j > 1 {
return true
}
}
}
return false
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
for i in 0..<n {
for j in 0..<n {
if i!= 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
for i in 0..<n {
for j in 0..<n {
if i!= j {
collisions += 1
}
}
}
return collisions
}
```
if i!= j { // use of '=' in a boolean context, did you mean '=='?
if i!= j { // '=' must have consistent whitespace on both sides
if i!= j { // cannot force unwrap value of non-optional type 'Int'
func carRaceCollision(n: Int) -> Int {
// TODO: implement this function
return 0
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: implement this function
return 0
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 0
var right = 0
for _ in 0..<n {
left += 1
right += 1
if left == right {
collisions += 1
left = 0
right = 0
}
}
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 = 0
var right = 0
for _ in 0..<n {
left += 1
right += 1
if left == right {
collisions += 1
left = 0
right = 0
}
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function
return 0
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function
return 0
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var cars = [Int](count: n, repeatedValue: 0)
var i = 0
var j = 0
while i < n && j < n {
if cars[i] == 0 {
i += 1
} else if cars[j] == 0 {
j += 1
} else {
cars[i] -= 1
cars[j] -= 1
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 cars = [Int](count: n, repeatedValue: 0)
var i = 0
var j = 0
while i < n && j < n {
if cars[i] == 0 {
i += 1
} else if cars[j] == 0 {
j += 1
} else {
cars[i] -= 1
cars[j] -= 1
collisions += 1
}
}
return collisions
}
```
var cars = [Int](count: n, repeatedValue: 0) // no exact matches in call to initializer
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement this function.
return 0
}
```
// XCTAssertTrue failed
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 {
var dict = [Int: Int]()
for num in l {
if let _ = dict[num] {
return true
}
dict[num * -1] = num
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for num in l {
if let _ = dict[num] {
return true
}
dict[num * -1] = num
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if let _ = dict[i] {
return true
} else {
dict[0 - i] = 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 dict = [Int: Int]()
for i in l {
if let _ = dict[i] {
return true
} else {
dict[0 - i] = i
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if let _ = dict[i] {
return true
} else {
dict[i * -1] = 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 dict = [Int: Int]()
for i in l {
if let _ = dict[i] {
return true
} else {
dict[i * -1] = i
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: implement pairsSumToZero
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 pairsSumToZero
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 pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return true
}
seen.insert(-i)
}
return false
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var 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 = ""
var remainder = x
while remainder > 0 {
result = "\(remainder % base)" + result
remainder /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = "\(remainder % base)" + result
remainder /= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
return String(x, radix: base)
}
```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 {
return String(x, radix: base)
}
```
func changeBase(x: Int, base: Int) -> String {
return String(x, radix: base)
}
```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 {
return String(x, radix: base)
}
```
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 = ""
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
var base = base
while x > 0 {
result = "\(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
var base = base
while x > 0 {
result = "\(x % base)" + result
x = x / base
}
return result
}
```
var base = base // variable 'base' was never mutated; consider changing to 'let' constant
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 = ""
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 {
return String(x, radix: base)
}
```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 {
return String(x, radix: base)
}
```
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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
}
```
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr =
XCTAssertTrue(fib4(n: 5) == 4) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 8) == 28) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 10) == 104) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 12) == 386) // cannot find 'fib4' in scope
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var ssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var ssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr =
XCTAssertTrue(fib4(n: 5) == 4) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 8) == 28) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 10) == 104) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 12) == 386) // cannot find 'fib4' in scope
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr =
XCTAssertTrue(fib4(n: 5) == 4) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 8) == 28) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 10) == 104) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 12) == 386) // cannot find 'fib4' in scope
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr =
XCTAssertTrue(fib4(n: 5) == 4) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 8) == 28) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 10) == 104) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 12) == 386) // cannot find 'fib4' in scope
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var ab = 0
var ac = 0
var ad = 0
var ae = 0
var af = 0
var ag = 0
var ah = 0
var ai = 0
var aj = 0
var ak = 0
var al = 0
var am = 0
var an = 0
var ao = 0
var ap = 0
var aq = 0
var ar = 0
var as = 0
var at = 0
var au = 0
var av = 0
var aw = 0
var ax = 0
var ay = 0
var az = 0
var ba = 0
var bb = 0
var bc = 0
var bd = 0
var be = 0
var bf = 0
var bg = 0
var bh = 0
var bi = 0
var bj = 0
var bk = 0
var bl = 0
var bm = 0
var bn = 0
var bo = 0
var bp = 0
var bq = 0
var br = 0
var bs = 0
var bt = 0
var bu = 0
var bv = 0
var bw = 0
var bx = 0
var by = 0
var bz = 0
var ca = 0
var cb = 0
var cc = 0
var cd = 0
var ce = 0
var cf = 0
var cg = 0
var ch = 0
var ci = 0
var cj = 0
var ck = 0
var cl = 0
var cm = 0
var cn = 0
var co = 0
var cp = 0
var cq = 0
var cr = 0
var cs = 0
var ct = 0
var cu = 0
var cv = 0
var cw = 0
var cx = 0
var cy = 0
var cz = 0
var da = 0
var db = 0
var dc = 0
var dd = 0
var de = 0
var df = 0
var dg = 0
var dh = 0
var di = 0
var dj = 0
var dk = 0
var dl = 0
var dm = 0
var dn = 0
var do = 0
var dp = 0
var dq = 0
var dr = 0
var ds = 0
var dt = 0
var du = 0
var dv = 0
var dw = 0
var dx = 0
var dy = 0
var dz = 0
var ea = 0
var eb = 0
var ec = 0
var ed = 0
var ee = 0
var ef = 0
var eg = 0
var eh = 0
var ei = 0
var ej = 0
var ek = 0
var el = 0
var em = 0
var en = 0
var eo = 0
var ep = 0
var eq = 0
var er = 0
var es = 0
var et = 0
var eu = 0
var ev = 0
var ew = 0
var ex = 0
var ey = 0
var ez = 0
var fa = 0
var fb = 0
var fc = 0
var fd = 0
var fe = 0
var ff = 0
var fg = 0
var fh = 0
var fi = 0
var fj = 0
var fk = 0
var fl = 0
var fm = 0
XCTAssertTrue(fib4(n: 5) == 4) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 8) == 28) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 10) == 104) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 12) == 386) // cannot find 'fib4' in scope
func fib4(n: Int) -> Int {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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 {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr =
XCTAssertTrue(fib4(n: 5) == 4) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 8) == 28) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 10) == 104) // cannot find 'fib4' in scope
XCTAssertTrue(fib4(n: 12) == 386) // cannot find 'fib4' in scope
func fib4(n: Int) -> Int {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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 {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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 fib4(n: Int) -> Int {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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 {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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]
}
fib4(n: 5)
fib4(n: 6)
fib4(n: 7)
```
// Fatal error: Index out of range
func fib4(n: Int) -> Int {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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 {
var fib4 = [Int](repeating: 0, count: n + 1)
fib4[0] = 0
fib4[1] = 0
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 {
return Double(l[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 {
return Double(l[l.count / 2])
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
return Double(sorted[mid])
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
return Double(sorted[mid])
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
return Double(l[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 {
return Double(l[l.count / 2])
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
return Double(l[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 {
return Double(l[l.count / 2])
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let middle = count / 2
if count % 2 == 0 {
return Double(sorted[middle - 1] + sorted[middle]) / 2.0
} else {
return Double(sorted[middle])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let middle = count / 2
if count % 2 == 0 {
return Double(sorted[middle - 1] + sorted[middle]) / 2.0
} else {
return Double(sorted[middle])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2] + sorted[count / 2 - 1]) / 2.0
} else {
return Double(sorted[count / 2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2] + sorted[count / 2 - 1]) / 2.0
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let middle = count / 2
return Double(sorted[middle])
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let middle = count / 2
return Double(sorted[middle])
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let mid = count / 2
if count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
}
return Double(sorted[mid])
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
let mid = count / 2
if count % 2 == 0 {
return Double(sorted[mid] + sorted[mid - 1]) / 2.0
}
return Double(sorted[mid])
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2] + sorted[count / 2 - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2] + sorted[count / 2 - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
return Double(sorted[mid])
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
return Double(sorted[mid])
}
```
// XCTAssertTrue failed
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```
func modp(n: Int, p: Int) -> Int {
return n & (p - 1)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n & (p - 1)
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
return n & (p - 1)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n & (p - 1)
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
return n & 0b1111
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n & 0b1111
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var 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
var p = p
var 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 modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var 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
var p = p
var 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 modp(n: Int, p: Int) -> Int {
var result = 1
var power = n
var mod = p
while power > 0 {
if power % 2 == 1 {
result = (result * mod) % p
}
power = power / 2
mod = (mod * mod) % 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 result = 1
var power = n
var mod = p
while power > 0 {
if power % 2 == 1 {
result = (result * mod) % p
}
power = power / 2
mod = (mod * mod) % p
}
return result
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var result = 1
var power = n
var mod = p
while power > 0 {
if (power & 1) == 1 {
result = (result * mod) % p
}
mod = (mod * mod) % p
power = power >> 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 result = 1
var power = n
var mod = p
while power > 0 {
if (power & 1) == 1 {
result = (result * mod) % p
}
mod = (mod * mod) % p
power = power >> 1
}
return result
}
```
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
while n > 0 {
if n % 2 == 1 {
result = (result * p) % p
}
n = 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 = 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 r = 1
while n > 0 {
if n % 2 == 1 {
r = (r * p) % p
}
n = n >> 1
p = (p * p) % p
}
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
var p = p
var r = 1
while n > 0 {
if n % 2 == 1 {
r = (r * p) % p
}
n = n >> 1
p = (p * p) % p
}
return r
}
```
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
return n & 0b1111
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n & 0b1111
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiou".contains(char) {
result.append(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiou".contains(char) {
result.append(char)
}
}
return result
}
```
if!"aeiou".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
return text.filter {!"aeiou".contains($0) }
}
```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 {!"aeiou".contains($0) }
}
```
// 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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 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
}
```
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
}
```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
}
```
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
}
```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 sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
s0 = s0.lowercased()
s1 = s1.lowercased()
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
if dict[char] == nil {
return false
}
dict[char]! -= 1
if dict[char] == 0 {
dict.removeValue(forKey: char)
}
}
return dict.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
s0 = s0.lowercased()
s1 = s1.lowercased()
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
if dict[char] == nil {
return false
}
dict[char]! -= 1
if dict[char] == 0 {
dict.removeValue(forKey: char)
}
}
return dict.isEmpty
}
```
dict[char] = (dict[char]?? 0) + 1 // expected ',' separator
dict[char] = (dict[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
dict[char] = (dict[char]?? 0) - 1
}
for value in dict.values {
if value!= 0 {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
dict[char] = (dict[char]?? 0) - 1
}
for value in dict.values {
if value!= 0 {
return false
}
}
return true
}
```
dict[char] = (dict[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) + 1 // expected ',' separator
dict[char] = (dict[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) - 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) - 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) - 1 // expected ',' separator
if value!= 0 { // '=' must have consistent whitespace on both sides
if value!= 0 { // cannot force unwrap value of non-optional type 'Int'
if value!= 0 { // use of '=' in a boolean context, did you mean '=='?
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
dict[char] = (dict[char]?? 0) - 1
}
return dict.values.allSatisfy { $0 == 0 }
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
dict[char] = (dict[char]?? 0) - 1
}
return dict.values.allSatisfy { $0 == 0 }
}
```
dict[char] = (dict[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) + 1 // expected ',' separator
dict[char] = (dict[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) - 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) - 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) - 1 // expected ',' separator
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
return Set(s0).isSubset(of: Set(s1))
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
return Set(s0).isSubset(of: Set(s1))
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
s0 = s0.lowercased()
s1 = s1.lowercased()
s0 = s0.sorted()
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 {
var s0 = s0
var s1 = s1
s0 = s0.lowercased()
s1 = s1.lowercased()
s0 = s0.sorted()
s1 = s1.sorted()
return s0 == s1
}
```
s0 = s0.sorted() // cannot assign value of type '[String.Element]' (aka 'Array<Character>') to type 'String'
s1 = s1.sorted() // cannot assign value of type '[String.Element]' (aka 'Array<Character>') to type 'String'
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
dict[char] = (dict[char]?? 0) - 1
}
for (_, count) in dict {
if count!= 0 {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var dict = [Character: Int]()
for char in s0 {
dict[char] = (dict[char]?? 0) + 1
}
for char in s1 {
dict[char] = (dict[char]?? 0) - 1
}
for (_, count) in dict {
if count!= 0 {
return false
}
}
return true
}
```
dict[char] = (dict[char]?? 0) + 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) + 1 // expected ',' separator
dict[char] = (dict[char]?? 0) + 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) - 1 // cannot convert value of type '(Int?, Int)' to expected argument type 'Int'
dict[char] = (dict[char]?? 0) - 1 // cannot use optional chaining on non-optional value of type 'Int'
dict[char] = (dict[char]?? 0) - 1 // expected ',' separator
if count!= 0 { // cannot force unwrap value of non-optional type 'Int'
if count!= 0 { // use of '=' in a boolean context, did you mean '=='?
if count!= 0 { // '=' must have consistent whitespace on both sides
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
return s0.sorted() == s1.sorted()
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
return Set(s0).isSubset(of: Set(s1))
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
return Set(s0).isSubset(of: Set(s1))
}
```
// XCTAssertTrue failed
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let c = a + b
a = b
b = c
}
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 c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let c = a + b
a = b
b = c
}
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 c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let c = a + b
a = b
b = c
}
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 c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 1...n {
let c = a + b
a = b
b = c
}
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 1...n {
let c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
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 {
var a = 0
var b = 1
for _ in 0..<n {
(a, b) = (b, a + b)
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let c = a + b
a = b
b = c
}
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 c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 1...n {
let c = a + b
a = b
b = c
}
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 1...n {
let c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 1...n {
let c = a + b
a = b
b = c
}
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 1...n {
let c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 1...n {
let c = a + b
a = b
b = c
}
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 1...n {
let c = a + b
a = b
b = c
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 1..<n {
let c = a + b
a = b
b = c
}
return b
}
```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 1..<n {
let c = a + b
a = b
b = c
}
return b
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
} 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 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 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 {
switch bracket {
case "<":
stack.append(bracket)
case ">":
if stack.isEmpty {
return false
}
stack.removeLast()
default:
break
}
}
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 {
switch bracket {
case "<":
stack.append(bracket)
case ">":
if stack.isEmpty {
return false
}
stack.removeLast()
default:
break
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if 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 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 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 monotonic(l: [Int]) -> Bool {
return l.sorted() == l || l.sorted(by: >)
}
```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 {
return l.sorted() == l || l.sorted(by: >)
}
```
return l.sorted() == l || l.sorted(by: >) // cannot convert value of type '[Int]' to expected argument type 'Bool'
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
var isMonotonic = true
for i in 1..<l.count {
if l[i] < prev {
isMonotonic = false
}
prev = l[i]
}
return isMonotonic
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
var isMonotonic = true
for i in 1..<l.count {
if l[i] < prev {
isMonotonic = false
}
prev = l[i]
}
return isMonotonic
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = false
var isIncreasing = false
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isDecreasing = true
} else if l[i] < l[i+1] {
isIncreasing = true
}
if isDecreasing && isIncreasing {
isMonotonic = false
break
}
}
return isMonotonic
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = false
var isIncreasing = false
for i in 0..<l.count-1 {
if l[i] > l[i+1] {
isDecreasing = true
} else if l[i] < l[i+1] {
isIncreasing = true
}
if isDecreasing && isIncreasing {
isMonotonic = false
break
}
}
return isMonotonic
}
```
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in 1..<l.count {
if l[i] > prev {
return false
}
prev = l[i]
}
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 {
var prev = l[0]
for i in 1..<l.count {
if l[i] > prev {
return false
}
prev = l[i]
}
return true
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
return l.count > 1 && l.sorted() == l || l.count > 1 && l.sorted(by: >) == l
}
```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 {
return l.count > 1 && l.sorted() == l || l.count > 1 && l.sorted(by: >) == l
}
```
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = false
var isIncreasing = false
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isDecreasing = true
} else if l[i] < l[i + 1] {
isIncreasing = true
}
if isDecreasing && isIncreasing {
isMonotonic = false
break
}
}
return isMonotonic
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = false
var isIncreasing = false
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isDecreasing = true
} else if l[i] < l[i + 1] {
isIncreasing = true
}
if isDecreasing && isIncreasing {
isMonotonic = false
break
}
}
return isMonotonic
}
```
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = false
var isIncreasing = false
for i in 0..<l.count-1 {
if l[i] == l[i+1] {
continue
}
if l[i] < l[i+1] {
isDecreasing = true
} else {
isIncreasing = true
}
if isDecreasing && isIncreasing {
isMonotonic = false
break
}
}
return isMonotonic
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isMonotonic = true
var isDecreasing = false
var isIncreasing = false
for i in 0..<l.count-1 {
if l[i] == l[i+1] {
continue
}
if l[i] < l[i+1] {
isDecreasing = true
} else {
isIncreasing = true
}
if isDecreasing && isIncreasing {
isMonotonic = false
break
}
}
return isMonotonic
}
```
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in 1..<l.count {
if l[i] > prev {
if l[i] < l[i-1] {
return false
}
} else if l[i] < prev {
if l[i] > l[i-1] {
return false
}
}
prev = l[i]
}
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 {
var prev = l[0]
for i in 1..<l.count {
if l[i] > prev {
if l[i] < l[i-1] {
return false
}
} else if l[i] < prev {
if l[i] > l[i-1] {
return false
}
}
prev = l[i]
}
return true
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
return l.reduce(true) { $0 && ($1 == $2 || $1 > $2) }
}
```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 {
return l.reduce(true) { $0 && ($1 == $2 || $1 > $2) }
}
```
return l.reduce(true) { $0 && ($1 == $2 || $1 > $2) } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func monotonic(l: [Int]) -> Bool {
return l.reduce(true) { $0 && ($1 == $2 || $1 > $2) }
}
```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 {
return l.reduce(true) { $0 && ($1 == $2 || $1 > $2) }
}
```
return l.reduce(true) { $0 && ($1 == $2 || $1 > $2) } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l1 {
dict[i] = 1
}
for i in l2 {
if dict[i]!= nil {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l1 {
dict[i] = 1
}
for i in l2 {
if dict[i]!= nil {
result.append(i)
}
}
return result
}
```
if dict[i]!= nil { // 'nil' cannot be assigned to type 'Int'
if dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if dict[i]!= nil { // '=' must have consistent whitespace on both sides
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }
}
```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) }
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
for i in 0..<l1.count {
if l1[i] == l2[i] {
result.append(l1[i])
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
for i in 0..<l1.count {
if l1[i] == l2[i] {
result.append(l1[i])
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
while l1.count > 0 && l2.count > 0 {
if l1[0] == l2[0] {
result.append(l1[0])
l1.removeFirst()
l2.removeFirst()
} else if l1[0] < l2[0] {
l1.removeFirst()
} else {
l2.removeFirst()
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
while l1.count > 0 && l2.count > 0 {
if l1[0] == l2[0] {
result.append(l1[0])
l1.removeFirst()
l2.removeFirst()
} else if l1[0] < l2[0] {
l1.removeFirst()
} else {
l2.removeFirst()
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l1 {
dict[i] = 1
}
for i in l2 {
if dict[i]!= nil {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l1 {
dict[i] = 1
}
for i in l2 {
if dict[i]!= nil {
result.append(i)
}
}
return result
}
```
if dict[i]!= nil { // 'nil' cannot be assigned to type 'Int'
if dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if dict[i]!= nil { // '=' must have consistent whitespace on both sides
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.sorted()
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.sorted()
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 0
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 0
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
n = n / i // cannot assign to value: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var largestPrime = 1
while i * i <= n {
if n % i == 0 {
largestPrime = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrime = n
}
return largestPrime
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var largestPrime = 1
while i * i <= n {
if n % i == 0 {
largestPrime = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrime = n
}
return largestPrime
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 0
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 0
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
while n % i == 0 {
n /= i
}
}
i += 1
}
if n > 1 {
largestPrimeFactor = n
}
return largestPrimeFactor
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
while n % i == 0 {
n /= i
}
i += 1
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
while n % i == 0 {
n /= i
}
i += 1
}
return n
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var number = n
var factor = 2
while number > 1 {
if number % factor == 0 {
largestPrimeFactor = factor
number = number / factor
} else {
factor += 1
}
}
return largestPrimeFactor
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var number = n
var factor = 2
while number > 1 {
if number % factor == 0 {
largestPrimeFactor = factor
number = number / factor
} else {
factor += 1
}
}
return largestPrimeFactor
}
```
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 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 {
switch bracket {
case "(":
stack.append(bracket)
case ")":
guard stack.count > 0 else { return false }
stack.removeLast()
default:
break
}
}
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 bracket in brackets {
switch bracket {
case "(":
stack.append(bracket)
case ")":
guard stack.count > 0 else { return false }
stack.removeLast()
default:
break
}
}
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
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for 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 stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if 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 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 derivative(xs: [Int]) -> [Int] {
return xs.enumerated().map { (i, x) in
return i == 0? 0 : x * i
}
}
```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 { (i, x) in
return i == 0? 0 : x * i
}
}
```
return i == 0? 0 : x * i // cannot convert value of type 'Bool' to closure result type 'Int'
return i == 0? 0 : x * i // consecutive statements on a line must be separated by ';'
return i == 0? 0 : x * i // cannot use optional chaining on non-optional value of type 'Int'
return i == 0? 0 : x * i // consecutive statements on a line must be separated by ';'
return i == 0? 0 : x * i // expected expression
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count - 1 {
result.append(xs[i] * (i + 1))
}
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 - 1 {
result.append(xs[i] * (i + 1))
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(i == 0? 0 : xs[i] * (i + 1))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(i == 0? 0 : xs[i] * (i + 1))
}
return result
}
```
result.append(i == 0? 0 : xs[i] * (i + 1)) // cannot convert value of type 'Bool' to expected argument type 'Int'
result.append(i == 0? 0 : xs[i] * (i + 1)) // cannot use optional chaining on non-optional value of type 'Int'
result.append(i == 0? 0 : xs[i] * (i + 1)) // extra argument in call
result.append(i == 0? 0 : xs[i] * (i + 1)) // expected ',' separator
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(i == 0? 0 : xs[i] * (i + 1))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(i == 0? 0 : xs[i] * (i + 1))
}
return result
}
```
result.append(i == 0? 0 : xs[i] * (i + 1)) // cannot convert value of type 'Bool' to expected argument type 'Int'
result.append(i == 0? 0 : xs[i] * (i + 1)) // cannot use optional chaining on non-optional value of type 'Int'
result.append(i == 0? 0 : xs[i] * (i + 1)) // extra argument in call
result.append(i == 0? 0 : xs[i] * (i + 1)) // expected ',' separator
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(i == 0? 0 : xs[i] * (i + 1))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(i == 0? 0 : xs[i] * (i + 1))
}
return result
}
```
result.append(i == 0? 0 : xs[i] * (i + 1)) // cannot convert value of type 'Bool' to expected argument type 'Int'
result.append(i == 0? 0 : xs[i] * (i + 1)) // cannot use optional chaining on non-optional value of type 'Int'
result.append(i == 0? 0 : xs[i] * (i + 1)) // extra argument in call
result.append(i == 0? 0 : xs[i] * (i + 1)) // expected ',' separator
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
result.append(xs[i] * (xs.count - i))
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count-1 {
result.append(xs[i+1] * (i+1))
}
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-1 {
result.append(xs[i+1] * (i+1))
}
return result
}
```
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```
// 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 + b + c)
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
(a, b, c) = (b, c, a + b + c)
}
return a
}
```
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var fib = [Int: Int]()
fib[0] = 0
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: Int]()
fib[0] = 0
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 a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
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
b = c
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
var a = 0
var b = 0
var c = 1
for _ in 0..<n {
a = b
b = c
c = a + b
}
return a
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { "aeiou".contains($0) }.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 {
return s.filter { "aeiou".contains($0) }.count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { "aeiou".contains($0) }.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 {
return s.filter { "aeiou".contains($0) }.count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { $0.isVowel }.count
}
extension Character {
var isVowel: Bool {
return ["a", "e", "i", "o", "u"].contains(String(self))
}
}
```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 {
return s.filter { $0.isVowel }.count
}
extension Character {
var isVowel: Bool {
return ["a", "e", "i", "o", "u"].contains(String(self))
}
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { $0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u" }.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 {
return s.filter { $0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u" }.count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { $0.isVowel }.count
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
}
```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 {
return s.filter { $0.isVowel }.count
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s.lowercased() {
if "aeiou".contains(char) {
vowels += 1
}
}
return vowels
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s.lowercased() {
if "aeiou".contains(char) {
vowels += 1
}
}
return vowels
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
let vowels = "aeiou"
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 {
var count = 0
let vowels = "aeiou"
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() {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s.lowercased() {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { "aeiou".contains($0) }.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 {
return s.filter { "aeiou".contains($0) }.count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
return s.filter { $0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u" }.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 {
return s.filter { $0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u" }.count
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = digits.suffix(digits.count - shift).append(digits.prefix(digits.count - shift))
return String(shiftedDigits.map { String($0) }.joined())
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = digits.suffix(digits.count - shift).append(digits.prefix(digits.count - shift))
return String(shiftedDigits.map { String($0) }.joined())
}
```
let shiftedDigits = digits.suffix(digits.count - shift).append(digits.prefix(digits.count - shift)) // cannot use mutating member on immutable value: function call returns immutable value
let shiftedDigits = digits.suffix(digits.count - shift).append(digits.prefix(digits.count - shift)) // missing argument label 'contentsOf:' in call
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = digits.map { $0 + shift }
return String(shiftedDigits.map { $0 % 10 })
}
```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 shiftedDigits = digits.map { $0 + shift }
return String(shiftedDigits.map { $0 % 10 })
}
```
return String(shiftedDigits.map { $0 % 10 }) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shifted = digits.map { $0 + shift }
return String(shifted.map { $0 % 10 })
}
```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 shifted = digits.map { $0 + shift }
return String(shifted.map { $0 % 10 })
}
```
return String(shifted.map { $0 % 10 }) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
let shifted = digits.map { $0 + digits.dropFirst(shift).joined() }
return shifted.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
let shifted = digits.map { $0 + digits.dropFirst(shift).joined() }
return shifted.joined()
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = digits.enumerated().map {
let index = $0.offset + shift
if index >= digits.count {
return digits[index - digits.count]
}
return digits[index]
}
return String(shiftedDigits.reversed())
}
```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 shiftedDigits = digits.enumerated().map {
let index = $0.offset + shift
if index >= digits.count {
return digits[index - digits.count]
}
return digits[index]
}
return String(shiftedDigits.reversed())
}
```
return String(shiftedDigits.reversed()) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = digits.map { $0 + shift }
return String(shiftedDigits.map { $0 % 10 })
}
```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 shiftedDigits = digits.map { $0 + shift }
return String(shiftedDigits.map { $0 % 10 })
}
```
return String(shiftedDigits.map { $0 % 10 }) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shifted = digits.enumerated().map { (index, digit) in
let shiftedDigit = (digit + shift) % 10
return shiftedDigit
}
return String(shifted.reversed())
}
```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 shifted = digits.enumerated().map { (index, digit) in
let shiftedDigit = (digit + shift) % 10
return shiftedDigit
}
return String(shifted.reversed())
}
```
return String(shifted.reversed()) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shifted = digits.map { $0 + shift }
return String(shifted.map { $0 % 10 })
}
```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 shifted = digits.map { $0 + shift }
return String(shifted.map { $0 % 10 })
}
```
return String(shifted.map { $0 % 10 }) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shifted = digits.map { $0 + shift }
return String(shifted.map { $0 % 10 })
}
```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 shifted = digits.map { $0 + shift }
return String(shifted.map { $0 % 10 })
}
```
return String(shifted.map { $0 % 10 }) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = digits.map { $0 + shift }
let shiftedDigitsReversed = shiftedDigits.reversed()
let shiftedDigitsReversedString = shiftedDigitsReversed.map { String($0) }.joined()
return shiftedDigitsReversedString
}
```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 shiftedDigits = digits.map { $0 + shift }
let shiftedDigitsReversed = shiftedDigits.reversed()
let shiftedDigitsReversedString = shiftedDigitsReversed.map { String($0) }.joined()
return shiftedDigitsReversedString
}
```
// 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.uppercased() {
sum += Int(char.asciiValue?? 0)
}
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.uppercased() {
sum += Int(char.asciiValue?? 0)
}
return sum
}
```
sum += Int(char.asciiValue?? 0) // no exact matches in call to initializer
sum += Int(char.asciiValue?? 0) // cannot use optional chaining on non-optional value of type 'UInt8'
sum += Int(char.asciiValue?? 0) // expected ',' separator
func digitSum(s: String) -> Int {
return s.uppercased().filter { $0.isLetter }.reduce(0) { $0 + Int(String($1).unicodeScalars.first!.value) }
}
```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.uppercased().filter { $0.isLetter }.reduce(0) { $0 + Int(String($1).unicodeScalars.first!.value) }
}
```
// 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 {
let charValue = Int(char.asciiValue!)
if charValue >= 65 && charValue <= 90 {
sum += charValue
}
}
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 {
let charValue = Int(char.asciiValue!)
if charValue >= 65 && charValue <= 90 {
sum += charValue
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
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 {
return s.uppercased().reduce(0) { $0 + Int(UnicodeScalar($1.asciiValue!).value) }
}
```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.uppercased().reduce(0) { $0 + Int(UnicodeScalar($1.asciiValue!).value) }
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
return s.uppercased().filter { $0.isLetter }.reduce(0) { $0 + Int(String($1).unicodeScalars.first!.value) }
}
```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.uppercased().filter { $0.isLetter }.reduce(0) { $0 + Int(String($1).unicodeScalars.first!.value) }
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
return s.uppercased().filter("A"..."Z").reduce(0, { $0 + Int(String($1).unicodeScalars.first!.value) })
}
```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.uppercased().filter("A"..."Z").reduce(0, { $0 + Int(String($1).unicodeScalars.first!.value) })
}
```
return s.uppercased().filter("A"..."Z").reduce(0, { $0 + Int(String($1).unicodeScalars.first!.value) }) // no exact matches in call to instance method 'filter'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
return 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: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
return apples + oranges
}
```
let apples = Int(fruits[0])?? 0 // consecutive statements on a line must be separated by ';'
let apples = Int(fruits[0])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let apples = Int(fruits[0])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let oranges = Int(fruits[1])?? 0 // consecutive statements on a line must be separated by ';'
return apples + oranges // cannot convert return expression of type 'String' to return type 'Int'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
let mango = apples + oranges
return mango >= n? mango - n : 0
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
let mango = apples + oranges
return mango >= n? mango - n : 0
}
```
let apples = Int(fruits[0])?? 0 // consecutive statements on a line must be separated by ';'
let apples = Int(fruits[0])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let apples = Int(fruits[0])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let oranges = Int(fruits[1])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // consecutive statements on a line must be separated by ';'
return mango >= n? mango - n : 0 // cannot convert return expression of type 'Bool' to return type 'Int'
return mango >= n? mango - n : 0 // cannot use optional chaining on non-optional value of type 'Int'
return mango >= n? mango - n : 0 // consecutive statements on a line must be separated by ';'
return mango >= n? mango - n : 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return mango >= n? mango - n : 0 // expected expression
return mango >= n? mango - n : 0 // consecutive statements on a line must be separated by ';'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = fruits[0].components(separatedBy: " ").first!
let oranges = fruits[1].components(separatedBy: " ").first!
let applesCount = Int(apples)!
let orangesCount = Int(oranges)!
let mangoCount = applesCount + orangesCount
return mangoCount > n? mangoCount - n : 0
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = fruits[0].components(separatedBy: " ").first!
let oranges = fruits[1].components(separatedBy: " ").first!
let applesCount = Int(apples)!
let orangesCount = Int(oranges)!
let mangoCount = applesCount + orangesCount
return mangoCount > n? mangoCount - n : 0
}
```
return mangoCount > n? mangoCount - n : 0 // consecutive statements on a line must be separated by ';'
return mangoCount > n? mangoCount - n : 0 // expected expression
return mangoCount > n? mangoCount - n : 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return mangoCount > n? mangoCount - n : 0 // cannot convert return expression of type 'Bool' to return type 'Int'
return mangoCount > n? mangoCount - n : 0 // cannot use optional chaining on non-optional value of type 'Int'
return mangoCount > n? mangoCount - n : 0 // result of operator '-' is unused
return mangoCount > n? mangoCount - n : 0 // consecutive statements on a line must be separated by ';'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
return (apples + oranges) - n
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
return (apples + oranges) - n
}
```
let apples = Int(fruits[0])?? 0 // consecutive statements on a line must be separated by ';'
let apples = Int(fruits[0])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let apples = Int(fruits[0])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let oranges = Int(fruits[1])?? 0 // consecutive statements on a line must be separated by ';'
return (apples + oranges) - n // cannot convert value of type 'String' to expected argument type 'Int'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = fruits[0].components(separatedBy: " ").first!
let oranges = fruits[1].components(separatedBy: " ").first!
let applesCount = Int(apples)!
let orangesCount = Int(oranges)!
var mangoCount = 0
for i in 0...applesCount {
if i + n >= 0 && i + n < applesCount {
mangoCount += 1
}
}
for i in 0...orangesCount {
if i + n >= 0 && i + n < orangesCount {
mangoCount += 1
}
}
return mangoCount
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = fruits[0].components(separatedBy: " ").first!
let oranges = fruits[1].components(separatedBy: " ").first!
let applesCount = Int(apples)!
let orangesCount = Int(oranges)!
var mangoCount = 0
for i in 0...applesCount {
if i + n >= 0 && i + n < applesCount {
mangoCount += 1
}
}
for i in 0...orangesCount {
if i + n >= 0 && i + n < orangesCount {
mangoCount += 1
}
}
return mangoCount
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[1])!
return 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: " and ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[1])!
return apples + oranges
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
let mango = apples + oranges
return mango >= n? mango - n : 0
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
let mango = apples + oranges
return mango >= n? mango - n : 0
}
```
let apples = Int(fruits[0])?? 0 // consecutive statements on a line must be separated by ';'
let apples = Int(fruits[0])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let apples = Int(fruits[0])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let oranges = Int(fruits[1])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // consecutive statements on a line must be separated by ';'
return mango >= n? mango - n : 0 // cannot convert return expression of type 'Bool' to return type 'Int'
return mango >= n? mango - n : 0 // cannot use optional chaining on non-optional value of type 'Int'
return mango >= n? mango - n : 0 // consecutive statements on a line must be separated by ';'
return mango >= n? mango - n : 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return mango >= n? mango - n : 0 // expected expression
return mango >= n? mango - n : 0 // consecutive statements on a line must be separated by ';'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
return 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: " and ")
let apples = Int(fruits[0])?? 0
let oranges = Int(fruits[1])?? 0
return apples + oranges
}
```
let apples = Int(fruits[0])?? 0 // consecutive statements on a line must be separated by ';'
let apples = Int(fruits[0])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let apples = Int(fruits[0])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // integer literal is unused
let oranges = Int(fruits[1])?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let oranges = Int(fruits[1])?? 0 // consecutive statements on a line must be separated by ';'
return apples + oranges // cannot convert return expression of type 'String' to return type 'Int'
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[1])!
return (apples + oranges) - n
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[1])!
return (apples + oranges) - n
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " and ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[1])!
return 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: " and ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[1])!
return apples + oranges
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```
if min!= Int.max { // '=' must have consistent whitespace on both sides
if min!= Int.max { // use of '=' in a boolean context, did you mean '=='?
if min!= Int.max { // cannot force unwrap value of non-optional type 'Int'
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < min {
min = value
minIndex = index
}
}
}
result.append(min)
result.append(minIndex)
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < min {
min = value
minIndex = index
}
}
}
result.append(min)
result.append(minIndex)
return result
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```
if min!= Int.max { // '=' must have consistent whitespace on both sides
if min!= Int.max { // use of '=' in a boolean context, did you mean '=='?
if min!= Int.max { // cannot force unwrap value of non-optional type 'Int'
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```
if min!= Int.max { // '=' must have consistent whitespace on both sides
if min!= Int.max { // use of '=' in a boolean context, did you mean '=='?
if min!= Int.max { // cannot force unwrap value of non-optional type 'Int'
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
if min!= Int.max {
result.append(min)
result.append(minIndex)
}
return result
}
```
if min!= Int.max { // '=' must have consistent whitespace on both sides
if min!= Int.max { // use of '=' in a boolean context, did you mean '=='?
if min!= Int.max { // cannot force unwrap value of non-optional type 'Int'
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var min = 0
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < min || min == 0 {
min = value
minIndex = index
}
}
}
return [min, minIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var min = 0
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < min || min == 0 {
min = value
minIndex = index
}
}
}
return [min, minIndex]
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```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 result = [Int]()
var min = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < min {
min = value
minIndex = index
}
}
result.append(min)
result.append(minIndex)
return result
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
for num in lst {
var count = 0
for n in lst {
if n == num {
count += 1
}
}
if count > max {
max = count
maxNum = num
}
}
if max >= maxNum {
return maxNum
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
for num in lst {
var count = 0
for n in lst {
if n == num {
count += 1
}
}
if count > max {
max = count
maxNum = num
}
}
if max >= maxNum {
return maxNum
} else {
return -1
}
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if dict[num] == nil {
dict[num] = 1
} else {
dict[num]! += 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if max < 2 {
return -1
}
return maxNum
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if dict[num] == nil {
dict[num] = 1
} else {
dict[num]! += 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if max < 2 {
return -1
}
return maxNum
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if let count = dict[num] {
dict[num] = count + 1
} else {
dict[num] = 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if max < 2 {
return -1
}
return maxNum
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if let count = dict[num] {
dict[num] = count + 1
} else {
dict[num] = 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if max < 2 {
return -1
}
return maxNum
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if let value = dict[i] {
dict[i] = value + 1
} else {
dict[i] = 1
}
}
for (key, value) in dict {
if value >= key {
return key + 1
}
}
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 value = dict[i] {
dict[i] = value + 1
} else {
dict[i] = 1
}
}
for (key, value) in dict {
if value >= key {
return key + 1
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxIndex = 0
for (index, value) in lst.enumerated() {
var count = 0
for i in lst {
if i == value {
count += 1
}
}
if count > max {
max = count
maxIndex = index
}
}
return maxIndex == 0? -1 : lst[maxIndex]
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxIndex = 0
for (index, value) in lst.enumerated() {
var count = 0
for i in lst {
if i == value {
count += 1
}
}
if count > max {
max = count
maxIndex = index
}
}
return maxIndex == 0? -1 : lst[maxIndex]
}
```
return maxIndex == 0? -1 : lst[maxIndex] // consecutive statements on a line must be separated by ';'
return maxIndex == 0? -1 : lst[maxIndex] // integer literal is unused
return maxIndex == 0? -1 : lst[maxIndex] // cannot convert return expression of type 'Bool' to return type 'Int'
return maxIndex == 0? -1 : lst[maxIndex] // cannot use optional chaining on non-optional value of type 'Int'
return maxIndex == 0? -1 : lst[maxIndex] // consecutive statements on a line must be separated by ';'
return maxIndex == 0? -1 : lst[maxIndex] // expected expression
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if dict[num] == nil {
dict[num] = 1
} else {
dict[num]! += 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if maxNum == 0 {
return -1
}
for (key, value) in dict {
if value == max && key > maxNum {
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 max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if dict[num] == nil {
dict[num] = 1
} else {
dict[num]! += 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if maxNum == 0 {
return -1
}
for (key, value) in dict {
if value == max && key > maxNum {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxIndex = 0
for (index, value) in lst.enumerated() {
var count = 0
for item in lst {
if item == value {
count += 1
}
}
if count > max {
max = count
maxIndex = index
}
}
if max > 0 {
return lst[maxIndex]
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxIndex = 0
for (index, value) in lst.enumerated() {
var count = 0
for item in lst {
if item == value {
count += 1
}
}
if count > max {
max = count
maxIndex = index
}
}
if max > 0 {
return lst[maxIndex]
} else {
return -1
}
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if let count = dict[num] {
dict[num] = count + 1
} else {
dict[num] = 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if max < 2 {
return -1
}
return maxNum
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxNum = 0
var dict = [Int: Int]()
for num in lst {
if let count = dict[num] {
dict[num] = count + 1
} else {
dict[num] = 1
}
if dict[num]! > max {
max = dict[num]!
maxNum = num
}
}
if max < 2 {
return -1
}
return maxNum
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if let _ = dict[i] {
dict[i]! += 1
} else {
dict[i] = 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 {
if let _ = dict[i] {
dict[i]! += 1
} else {
dict[i] = 1
}
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
if let _ = dict[num] {
dict[num]! += 1
} else {
dict[num] = 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 num in lst {
if let _ = dict[num] {
dict[num]! += 1
} else {
dict[num] = 1
}
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var min = lst.min()
var max = lst.max()
while min!= nil {
result.append(min!)
result.append(max!)
min = lst.min()
max = lst.max()
lst.remove(at: lst.index(of: min!)!)
lst.remove(at: lst.index(of: max!)!)
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var min = lst.min()
var max = lst.max()
while min!= nil {
result.append(min!)
result.append(max!)
min = lst.min()
max = lst.max()
lst.remove(at: lst.index(of: min!)!)
lst.remove(at: lst.index(of: max!)!)
}
return result
}
```
while min!= nil { // 'nil' cannot be assigned to type 'Int'
while min!= nil { // '=' must have consistent whitespace on both sides
while min!= nil { // use of '=' in a boolean context, did you mean '=='?
lst.remove(at: lst.index(of: min!)!) // cannot use mutating member on immutable value: 'lst' is a 'let' constant
lst.remove(at: lst.index(of: max!)!) // cannot use mutating member on immutable value: 'lst' is a 'let' constant
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
result.sort()
var min = result.removeFirst()
var max = result.removeLast()
var res = [Int]()
res.append(min)
res.append(max)
while result.count > 0 {
min = result.removeFirst()
max = result.removeLast()
res.append(min)
res.append(max)
}
return res
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
result.sort()
var min = result.removeFirst()
var max = result.removeLast()
var res = [Int]()
res.append(min)
res.append(max)
while result.count > 0 {
min = result.removeFirst()
max = result.removeLast()
res.append(min)
res.append(max)
}
return res
}
```
// Fatal error: Can't remove last element from an empty collection
func strangeSortList(lst: [Int]) -> [Int] {
return lst.sorted { $0 < $1 }
}
```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] {
return lst.sorted { $0 < $1 }
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst
var min = sorted.removeFirst()
var max = sorted.removeLast()
var result = [min, max]
while sorted.count > 0 {
min = sorted.removeFirst()
max = sorted.removeLast()
result.append(min)
result.append(max)
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst
var min = sorted.removeFirst()
var max = sorted.removeLast()
var result = [min, max]
while sorted.count > 0 {
min = sorted.removeFirst()
max = sorted.removeLast()
result.append(min)
result.append(max)
}
return result
}
```
// Fatal error: Can't remove last element from an empty collection
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
var min = lst.min()
var max = lst.max()
var minIndex = lst.firstIndex(of: min!)
var maxIndex = lst.firstIndex(of: max!)
var minValue = lst[minIndex!]
var maxValue = lst[maxIndex!]
result[minIndex!] = maxValue
result[maxIndex!] = minValue
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
var min = lst.min()
var max = lst.max()
var minIndex = lst.firstIndex(of: min!)
var maxIndex = lst.firstIndex(of: max!)
var minValue = lst[minIndex!]
var maxValue = lst[maxIndex!]
result[minIndex!] = maxValue
result[maxIndex!] = minValue
return result
}
```
var min = lst.min() // variable 'min' was never mutated; consider changing to 'let' constant
var max = lst.max() // variable 'max' was never mutated; consider changing to 'let' constant
var minIndex = lst.firstIndex(of: min!) // variable 'minIndex' was never mutated; consider changing to 'let' constant
var maxIndex = lst.firstIndex(of: max!) // variable 'maxIndex' was never mutated; consider changing to 'let' constant
var minValue = lst[minIndex!] // variable 'minValue' was never mutated; consider changing to 'let' constant
var maxValue = lst[maxIndex!] // variable 'maxValue' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
return lst.sorted { $0 < $1 }
}
```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] {
return lst.sorted { $0 < $1 }
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
return lst.sorted { $0 < $1 }
}
```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] {
return lst.sorted { $0 < $1 }
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst
var min = 0
var max = 0
var minIndex = 0
var maxIndex = 0
var temp = 0
var tempIndex = 0
for i in 0..<sorted.count {
if sorted[i] < sorted[min] {
min = i
minIndex = i
} else if sorted[i] > sorted[max] {
max = i
maxIndex = i
}
}
temp = sorted[min]
sorted[min] = sorted[max]
sorted[max] = temp
temp = sorted[minIndex]
sorted[minIndex] = sorted[maxIndex]
sorted[maxIndex] = temp
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 = lst
var min = 0
var max = 0
var minIndex = 0
var maxIndex = 0
var temp = 0
var tempIndex = 0
for i in 0..<sorted.count {
if sorted[i] < sorted[min] {
min = i
minIndex = i
} else if sorted[i] > sorted[max] {
max = i
maxIndex = i
}
}
temp = sorted[min]
sorted[min] = sorted[max]
sorted[max] = temp
temp = sorted[minIndex]
sorted[minIndex] = sorted[maxIndex]
sorted[maxIndex] = temp
return sorted
}
// 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
var min = 0
var max = 0
var minIndex = 0
var maxIndex = 0
var temp = 0
var tempIndex = 0
for i in 0..<sorted.count {
if sorted[i] < sorted[min] {
min = i
minIndex = i
} else if sorted[i] > sorted[max] {
max = i
maxIndex = i
}
}
temp = sorted[min]
sorted[min] = sorted[max]
sorted[max] = temp
temp = sorted[minIndex]
sorted[minIndex] = sorted[maxIndex]
sorted[maxIndex] = temp
return sorted
}
// 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
var min = 0
var max = 0
var minIndex = 0
var maxIndex = 0
var temp = 0
var tempIndex = 0
for i in 0..<sorted.count {
if sorted[i] < sorted[min] {
min = i
minIndex = i
} else if sorted[i] > sorted[max] {
max = i
maxIndex = i
}
}
temp = sorted[min]
sorted[min] = sorted[max]
sorted[max] = temp
temp = sorted[minIndex]
sorted[minIndex] = sorted[maxIndex]
sorted[maxIndex] = temp
return sorted
}
// 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
var min = 0
var max = 0
var minIndex = 0
var maxIndex = 0
var temp = 0
var tempIndex = 0
for i in 0..<sorted.count {
if sorted[i] < sorted[min] {
min = i
minIndex = i
} else if sorted[i] > sorted[max] {
max =
var tempIndex = 0 // initialization of variable 'tempIndex' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
var min = lst.min()
var max = lst.max()
var minIndex = lst.firstIndex(of: min!)
var maxIndex = lst.firstIndex(of: max!)
var minCount = 0
var maxCount = 0
var minCountIndex = 0
var maxCountIndex = 0
var minCountMaxIndex = 0
var maxCountMinIndex = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount = 0
var maxCountMinIndexCount = 0
var minCountMaxIndexCount
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [] as [Int]) == [] as [Int]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8]) == [1, 8, 2, 7, 3, 6, 4, 5]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [0, 2, 2, 2, 5, 5, -5, -5]) == [-5, 5, -5, 5, 0, 2, 2, 2]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [111111]) == [111111]) // cannot find 'strangeSortList' in scope
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
var min = lst.min()!
var max = lst.max()!
var minIndex = lst.firstIndex(of: min)!
var maxIndex = lst.firstIndex(of: max)!
var minCount = 0
var maxCount = 0
var minIndexCount = 0
var maxIndexCount = 0
var minIndexCount2 = 0
var maxIndexCount2 = 0
var minIndexCount3 = 0
var maxIndexCount3 = 0
var minIndexCount4 = 0
var maxIndexCount4 = 0
var minIndexCount5 = 0
var maxIndexCount5 = 0
var minIndexCount6 = 0
var maxIndexCount6 = 0
var minIndexCount7 = 0
var maxIndexCount7 = 0
var minIndexCount8 = 0
var maxIndexCount8 = 0
var minIndexCount9 = 0
var maxIndexCount9 = 0
var minIndexCount10 = 0
var maxIndexCount10 = 0
var minIndexCount11 = 0
var maxIndexCount11 = 0
var minIndexCount12 = 0
var maxIndexCount12 = 0
var minIndexCount13 = 0
var maxIndexCount13 = 0
var minIndexCount14 = 0
var maxIndexCount14 = 0
var minIndexCount15 = 0
var maxIndexCount15 = 0
var minIndexCount16 = 0
var maxIndexCount16 = 0
var minIndexCount17 = 0
var maxIndexCount17 = 0
var minIndexCount18 = 0
var maxIndexCount18 = 0
var minIndexCount19 = 0
var maxIndexCount19 = 0
var minIndexCount20 = 0
var maxIndexCount20 = 0
var minIndexCount21 = 0
var maxIndexCount21 = 0
var minIndexCount22 = 0
var maxIndexCount22 = 0
var minIndexCount23 = 0
var maxIndexCount23 = 0
var minIndexCount24 = 0
var maxIndexCount24 = 0
var minIndexCount25 = 0
var maxIndexCount25 = 0
var minIndexCount26 = 0
var maxIndexCount26 = 0
var minIndexCount27 = 0
var maxIndexCount27 = 0
var minIndexCount28 = 0
var maxIndexCount28 = 0
var minIndexCount29 = 0
var maxIndexCount29 = 0
var minIndexCount30 = 0
var maxIndexCount30 = 0
var minIndexCount31 = 0
var maxIndexCount31 = 0
var minIndexCount32 = 0
var maxIndexCount32 = 0
var minIndexCount33 = 0
var maxIndexCount33 = 0
var minIndexCount34 = 0
var maxIndexCount34 = 0
var minIndexCount35 = 0
var maxIndexCount35 = 0
var minIndexCount36 = 0
var maxIndexCount36 = 0
var minIndexCount37 = 0
var maxIndexCount37 = 0
var minIndexCount38 = 0
var maxIndexCount38 = 0
var minIndexCount39 = 0
var maxIndexCount39 = 0
var minIndexCount40 = 0
var maxIndexCount40 = 0
var minIndexCount41 = 0
var maxIndexCount41 = 0
var minIndexCount42 = 0
var maxIndexCount42 = 0
var minIndexCount43 = 0
var maxIndexCount43 = 0
var minIndexCount44 = 0
var maxIndexCount44 = 0
var minIndexCount45 = 0
var maxIndexCount45 = 0
var minIndexCount46 = 0
var maxIndexCount46 = 0
var minIndexCount47 = 0
var maxIndexCount47 = 0
var minIndexCount48 = 0
var maxIndexCount48 = 0
var minIndexCount49 = 0
var maxIndexCount49 =
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [] as [Int]) == [] as [Int]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8]) == [1, 8, 2, 7, 3, 6, 4, 5]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [0, 2, 2, 2, 5, 5, -5, -5]) == [-5, 5, -5, 5, 0, 2, 2, 2]) // cannot find 'strangeSortList' in scope
XCTAssertTrue(strangeSortList(lst: [111111]) == [111111]) // cannot find 'strangeSortList' in scope
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```
} // missing return in global function expected to return 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```
} // missing return in global function expected to return 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
return 0.0
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
return 0.0
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sorted = sides.sorted()
let (a, b, c) = (sorted[0], sorted[1], sorted[2])
let sum = a + b
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sides = [a, b, c]
let sorted = sides.sorted()
let (a, b, c) = (sorted[0], sorted[1], sorted[2])
let sum = a + b
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1
}
```
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1 // consecutive statements on a line must be separated by ';'
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1 // expected expression
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1 // cannot convert return expression of type 'Optional<_>' to return type 'Double'
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1 // cannot call value of non-function type 'Bool'
return (sum > c)? (0.5 * Double(a) * Double(b)).rounded() : -1 // cannot use optional chaining on non-optional value of type 'Bool'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Write your code here
}
```
} // missing return in global function expected to return 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - 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 {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```
let area = sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - 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 {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```
let area = sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - 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 {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```
let area = sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - 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 {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```
let area = sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - 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 {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```
let area = sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
var q = q
q.sort()
for i in 0..<q.count {
sum += q[i]
if sum > w {
return false
}
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
var q = q
q.sort()
for i in 0..<q.count {
sum += q[i]
if sum > w {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = (w - sum) / 2
return q.reduce(true, { $0 && $1 <= maxWeight })
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = (w - sum) / 2
return q.reduce(true, { $0 && $1 <= maxWeight })
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = w - sum
return q.reduce(true, { $0 && $1 == $1.reversed() && $1 <= maxWeight })
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let maxWeight = w - sum
return q.reduce(true, { $0 && $1 == $1.reversed() && $1 <= maxWeight })
}
```
return q.reduce(true, { $0 && $1 == $1.reversed() && $1 <= maxWeight }) // value of type 'Int' has no member 'reversed'
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q.count == q.count(where: { $0 == $0.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.count == q.count(where: { $0 == $0.reversed() })
}
```
return sum <= w && q.count == q.count(where: { $0 == $0.reversed() }) // generic parameter 'Element' could not be inferred
return sum <= w && q.count == q.count(where: { $0 == $0.reversed() }) // cannot call value of non-function type 'Int'
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q.reduce(true) { $0 && $1 == $2 }
return isBalanced && sum <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q.reduce(true) { $0 && $1 == $2 }
return isBalanced && sum <= w
}
```
let isBalanced = q.reduce(true) { $0 && $1 == $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q.reduce(true) { $0 && $1 == $2 }
return isBalanced && sum <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q.reduce(true) { $0 && $1 == $2 }
return isBalanced && sum <= w
}
```
let isBalanced = q.reduce(true) { $0 && $1 == $2 } // contextual closure type '(Bool, Int) throws -> Bool' expects 2 arguments, but 3 were used in closure body
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, +) <= w && q.reduce(0, +) == q.reduce(0, +)
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, +) <= w && q.reduce(0, +) == q.reduce(0, +)
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, +) <= w && q.reduce(0, +) == q.reduce(0, { $0 + $1 })
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, +) <= w && q.reduce(0, +) == q.reduce(0, { $0 + $1 })
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q.count == q.countOfBalancedArray()
}
extension Array {
func countOfBalancedArray() -> Int {
var count = 0
for i in 0..<self.count {
if self[i] == self[self.count - 1 - i] {
count += 1
}
}
return count
}
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
return sum <= w && q.count == q.countOfBalancedArray()
}
extension Array {
func countOfBalancedArray() -> Int {
var count = 0
for i in 0..<self.count {
if self[i] == self[self.count - 1 - i] {
count += 1
}
}
return count
}
}
```
if self[i] == self[self.count - 1 - i] { // referencing operator function '==' on 'Equatable' requires that 'Element' conform to 'Equatable'
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, +) <= w && q.reduce(0, +) == q.reduce(0, +)
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, +) <= w && q.reduce(0, +) == q.reduce(0, +)
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var changes = 0
while left < right {
if arr[left]!= arr[right] {
changes += 1
right -= 1
} else {
left += 1
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] {
changes += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return changes
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var changes = 0
while left < right {
if arr[left]!= arr[right] {
changes += 1
right -= 1
} else {
left += 1
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] {
changes += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return changes
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var left = 0
var right = arr.count - 1
var count = 0
while left < right {
if arr[left]!= arr[right] {
count += 1
right -= 1
} else {
left += 1
right -= 1
}
}
return count
}
```
if arr[left]!= arr[right] { // use of '=' in a boolean context, did you mean '=='?
if arr[left]!= arr[right] { // '=' must have consistent whitespace on both sides
if arr[left]!= arr[right] { // cannot force unwrap value of non-optional type 'Int'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var lst1 = lst1
var lst2 = lst2
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var lst1 = lst1
var lst2 = lst2
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```
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
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
let str1 = lst1[i]
let str2 = lst2[i]
let count1 = str1.count
let count2 = str2.count
if count1 < count2 {
result.append(str1)
} else if count1 > count2 {
result.append(str2)
} else {
result.append(str1)
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
let str1 = lst1[i]
let str2 = lst2[i]
let count1 = str1.count
let count2 = str2.count
if count1 < count2 {
result.append(str1)
} else if count1 > count2 {
result.append(str2)
} else {
result.append(str1)
}
}
return result
}
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
}
for i in 0..<min {
if minArr[i].count < maxArr[i].count {
result.append(minArr[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
}
for i in 0..<min {
if minArr[i].count < maxArr[i].count {
result.append(minArr[i])
}
}
return result
}
totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"])
totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"])
totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"])
totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"])
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var count = 0
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
var minArrCount = 0
var maxArrCount = 0
var minArrIndex = 0
var maxArrIndex = 0
if lst1.count > lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
minArrCount = lst1.count
maxArrCount = lst2.count
minArrIndex = 0
maxArrIndex = 0
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
minArrCount = lst2.count
maxArrCount = lst1.count
minArrIndex = 0
maxArrIndex = 0
}
for i in 0..<min {
count = 0
for j in 0..<max {
if minArr[i].lowercased() == maxArr[j].lowercased() {
count += 1
}
}
if count < minArrCount {
minArrCount = count
minArrIndex = i
}
}
for i in 0..<max {
count = 0
for j in 0..<min {
if maxArr[i].lowercased() == minArr[j].lowercased() {
count += 1
}
}
if count < maxArrCount {
maxArrCount = count
maxArrIndex = i
}
}
if minArrCount < maxArrCount {
for i in 0..<minArrCount {
result.append(minArr[minArrIndex])
minArrIndex += 1
}
} else {
for i in 0..<maxArrCount {
result.append(maxArr[maxArrIndex])
maxArrIndex += 1
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var count = 0
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
var minArrCount = 0
var maxArrCount = 0
var minArrIndex = 0
var maxArrIndex = 0
if lst1.count > lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
minArrCount = lst1.count
maxArrCount = lst2.count
minArrIndex = 0
maxArrIndex = 0
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
minArrCount = lst2.count
maxArrCount = lst1.count
minArrIndex = 0
maxArrIndex = 0
}
for i in 0..<min {
count = 0
for j in 0..<max {
if minArr[i].lowercased() == maxArr[j].lowercased() {
count += 1
}
}
if count < minArrCount {
minArrCount = count
minArrIndex = i
}
}
for i in 0..<max {
count = 0
for j in 0..<min {
if maxArr[i].lowercased() == minArr[j].lowercased() {
count += 1
}
}
if count < maxArrCount {
maxArrCount = count
maxArrIndex = i
}
}
if minArrCount < maxArrCount {
for i in 0..<minArrCount {
result.append(minArr[minArrIndex])
minArrIndex += 1
}
} else {
for i in 0..<maxArrCount {
result.append(maxArr[maxArrIndex])
maxArrIndex += 1
}
}
return result
}
```
for i in 0..<minArrCount { // immutable value 'i' was never used; consider replacing with '_' or removing it
for i in 0..<maxArrCount { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"])
totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"])
totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"])
totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"])
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
}
for i in 0..<min {
if minArr[i].count < maxArr[i].count {
result.append(minArr[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
}
for i in 0..<min {
if minArr[i].count < maxArr[i].count {
result.append(minArr[i])
}
}
return result
}
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
} else {
min = lst2.count
max = lst1.count
}
for i in 0..<min {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
var minArrCount = 0
var maxArrCount = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
}
for i in 0..<min {
minArrCount += minArr[i].count
maxArrCount += maxArr[i].count
}
if minArrCount < maxArrCount {
result = minArr
} else {
result = maxArr
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
var min = 0
var max = 0
var minArr = [String]()
var maxArr = [String]()
var minArrCount = 0
var maxArrCount = 0
if lst1.count < lst2.count {
min = lst1.count
max = lst2.count
minArr = lst1
maxArr = lst2
} else {
min = lst2.count
max = lst1.count
minArr = lst2
maxArr = lst1
}
for i in 0..<min {
minArrCount += minArr[i].count
maxArrCount += maxArr[i].count
}
if minArrCount < maxArrCount {
result = minArr
} else {
result = maxArr
}
return result
}
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
return lst1.filter { $0.count < lst2.filter { $0.count == $1.count }.count }
}
```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] {
return lst1.filter { $0.count < lst2.filter { $0.count == $1.count }.count }
}
```
return lst1.filter { $0.count < lst2.filter { $0.count == $1.count }.count } // contextual closure type '(String) throws -> Bool' expects 1 argument, but 2 were used in closure body
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var i = 2
while i < a {
if a % i == 0 {
if isPrime(a: i) {
return true
}
}
i += 1
}
return false
}
func isPrime(a: Int) -> Bool {
var i = 2
while i < a {
if a % i == 0 {
return false
}
i += 1
}
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 {
var i = 2
while i < a {
if a % i == 0 {
if isPrime(a: i) {
return true
}
}
i += 1
}
return false
}
func isPrime(a: Int) -> Bool {
var i = 2
while i < a {
if a % i == 0 {
return false
}
i += 1
}
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == Int(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 == Int(pow(Double(n), Double(x)))
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == Int(pow(Double(n), Double(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 == Int(pow(Double(n), Double(Int(log(Double(x)) / log(Double(n))))))
}
```
// 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.0/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.0/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 Int(pow(Double(a), 1.0/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.0/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 (Int(pow(Double(a), 1.0/3.0)) == a)? true : 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 {
return (Int(pow(Double(a), 1.0/3.0)) == a)? true : false
}
```
return (Int(pow(Double(a), 1.0/3.0)) == a)? true : false // boolean literal is unused
return (Int(pow(Double(a), 1.0/3.0)) == a)? true : false // consecutive statements on a line must be separated by ';'
return (Int(pow(Double(a), 1.0/3.0)) == a)? true : false // cannot use optional chaining on non-optional value of type 'Bool'
return (Int(pow(Double(a), 1.0/3.0)) == a)? true : false // consecutive statements on a line must be separated by ';'
return (Int(pow(Double(a), 1.0/3.0)) == a)? true : false // expected expression
func iscube(a: Int) -> Bool {
return Int(pow(Double(a), 1.0 / 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.0 / 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 Int(pow(Double(a), 1.0/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.0/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 Int(pow(Double(a), 1.0/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.0/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 Int(pow(Double(a), 1.0 / 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.0 / 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 Int(pow(Double(a), 1.0 / 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.0 / 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 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)) == a
}
```
// 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.0/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.0/3.0)) == a
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for char in num {
if hex.contains(char) {
let index = hex.index(of: char)
let decimal = hex.distance(from: hex.startIndex, to: index!)
if isPrime(decimal) {
count += 1
}
}
}
return count
}
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 have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for char in num {
if hex.contains(char) {
let index = hex.index(of: char)
let decimal = hex.distance(from: hex.startIndex, to: index!)
if isPrime(decimal) {
count += 1
}
}
}
return count
}
func isPrime(_ num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
let index = hex.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
func hexKey(num: String) -> Int {
var result = 0
let hex = "0123456789ABCDEF"
for char in num {
if hex.contains(char) {
if isPrime(Int(String(char))!) {
result += 1
}
}
}
return result
}
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 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 result = 0
let hex = "0123456789ABCDEF"
for char in num {
if hex.contains(char) {
if isPrime(Int(String(char))!) {
result += 1
}
}
}
return result
}
func isPrime(_ num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func hexKey(num: String) -> Int {
var count = 0
let hex = "0123456789ABCDEF"
for char in num {
if hex.contains(char) {
if isPrime(num: Int(String(char))!) {
count += 1
}
}
}
return count
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You 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
let hex = "0123456789ABCDEF"
for char in num {
if hex.contains(char) {
if isPrime(num: Int(String(char))!) {
count += 1
}
}
}
return count
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func hexKey(num: String) -> Int {
var result = 0
let hex = "0123456789ABCDEF"
for char in num {
if hex.contains(char) {
let index = hex.firstIndex(of: char)
let value = hex.distance(from: hex.startIndex, to: index!)
if isPrime(value) {
result += 1
}
}
}
return result
}
func isPrime(_ value: Int) -> Bool {
if value < 2 { return false }
if value == 2 { return true }
if value % 2 == 0 { return false }
for i in 3..<value {
if value % i == 0 {
return false
}
}
return true
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var result = 0
let hex = "0123456789ABCDEF"
for char in num {
if hex.contains(char) {
let index = hex.firstIndex(of: char)
let value = hex.distance(from: hex.startIndex, to: index!)
if isPrime(value) {
result += 1
}
}
}
return result
}
func isPrime(_ value: Int) -> Bool {
if value < 2 { return false }
if value == 2 { return true }
if value % 2 == 0 { return false }
for i in 3..<value {
if value % i == 0 {
return false
}
}
return true
}
```
func hexKey(num: String) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
let hex = "0123456789ABCDEF"
for i in 0..<num.count {
let index = hex.index(hex.startIndex, offsetBy: i)
let char = hex[index]
if isPrime(char) {
count += 1
}
}
return count
}
func isPrime(_ num: Character) -> Bool {
let num = Int(String(num))!
if num == 2 || num == 3 || num == 5 || num == 7 {
return true
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
let hex = "0123456789ABCDEF"
for i in 0..<num.count {
let index = hex.index(hex.startIndex, offsetBy: i)
let char = hex[index]
if isPrime(char) {
count += 1
}
}
return count
}
func isPrime(_ num: Character) -> Bool {
let num = Int(String(num))!
if num == 2 || num == 3 || num == 5 || num == 7 {
return true
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func hexKey(num: String) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
return 0
}
```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 {
return 0
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var result = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
result += 1
}
}
return result
}
```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 result = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
result += 1
}
}
return result
}
```
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(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 = String(decimal % 2) + binary
decimal = 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 decimalToBinary(decimal: Int) -> String {
return "db\(String(decimal, radix: 2))db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
return "db\(String(decimal, radix: 2))db"
}
```
func decimalToBinary(decimal: Int) -> String {
return "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 {
binary = String(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 = String(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 = String(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 = String(decimal % 2) + binary
decimal = decimal / 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var num = decimal
while num > 0 {
binary = "\(num % 2)\(binary)"
num /= 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 num = decimal
while num > 0 {
binary = "\(num % 2)\(binary)"
num /= 2
}
return "db\(binary)db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var num = decimal
while num > 0 {
binary = String(num % 2) + binary
num /= 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 num = decimal
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var num = decimal
while num > 0 {
binary = String(num % 2) + binary
num /= 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 num = decimal
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return "db" + binary + "db"
}
// 1. Write a function that takes in a string and returns the number of vowels in the string.
// 2. Write a function that takes in a string and returns the number of consonants in the string.
// 3. Write a function that takes in a string and returns the number of unique characters in the string.
// 4. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 5. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 6. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 7. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 8. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 9. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 10. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 11. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 12. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 13. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 14. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 15. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 16. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 17. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 18. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 19. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 20. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 21. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 22. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 23. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 24. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 25. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 26. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 27. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 28. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 29. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 30. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 31. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 32. Write a function that takes in a string and returns the number of characters that are not vowels or consonants.
// 33. Write
// 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 {
var set = Set<Character>()
for char in s {
set.insert(char)
}
return set.count >= 3
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for char in s {
set.insert(char)
}
return set.count >= 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
let chars = s.map { String($0) }
return chars.allSatisfy { chars.firstIndex(of: $0) == chars.lastIndex(of: $0) }
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
guard s.count >= 3 else { return false }
let chars = s.map { String($0) }
return chars.allSatisfy { chars.firstIndex(of: $0) == chars.lastIndex(of: $0) }
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
let set = Set(s)
return set.count == s.count
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let set = Set(s)
return set.count == s.count
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```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 {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```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 {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```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 {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```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 {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```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 {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
let chars = s.map { String($0) }
let charsSet = Set(chars)
return charsSet.count == 3
}
```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 chars = s.map { String($0) }
let charsSet = Set(chars)
return charsSet.count == 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```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 {
return s.count >= 3 && Set(s.prefix(3)).count == 3
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for 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 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 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 letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
switch grade {
case 4.0:
result.append("A+")
case 3.7:
result.append("A")
case 3.3:
result.append("A-")
case 3.0:
result.append("B+")
case 2.7:
result.append("B")
case 2.3:
result.append("B-")
case 2.0:
result.append("C+")
case 1.7:
result.append("C")
case 1.3:
result.append("C-")
case 1.0:
result.append("D+")
case 0.7:
result.append("D")
case 0.0:
result.append("D-")
default:
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
switch grade {
case 4.0:
result.append("A+")
case 3.7:
result.append("A")
case 3.3:
result.append("A-")
case 3.0:
result.append("B+")
case 2.7:
result.append("B")
case 2.3:
result.append("B-")
case 2.0:
result.append("C+")
case 1.7:
result.append("C")
case 1.3:
result.append("C-")
case 1.0:
result.append("D+")
case 0.7:
result.append("D")
case 0.0:
result.append("D-")
default:
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
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 letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for 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 result = [String]()
for grade in grades {
switch grade {
case 4.0:
result.append("A+")
case 3.7:
result.append("A")
case 3.3:
result.append("A-")
case 3.0:
result.append("B+")
case 2.7:
result.append("B")
case 2.3:
result.append("B-")
case 2.0:
result.append("C+")
case 1.7:
result.append("C")
case 1.3:
result.append("C-")
case 1.0:
result.append("D+")
case 0.7:
result.append("D")
case 0.0:
result.append("D-")
default:
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
switch grade {
case 4.0:
result.append("A+")
case 3.7:
result.append("A")
case 3.3:
result.append("A-")
case 3.0:
result.append("B+")
case 2.7:
result.append("B")
case 2.3:
result.append("B-")
case 2.0:
result.append("C+")
case 1.7:
result.append("C")
case 1.3:
result.append("C-")
case 1.0:
result.append("D+")
case 0.7:
result.append("D")
case 0.0:
result.append("D-")
default:
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
return string.count.isPrime
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return string.count.isPrime
}
```
return string.count.isPrime // value of type 'Int' has no member 'isPrime'
func primeLength(string: String) -> Bool {
// Write your code here
}
```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 {
// Write your code here
}
```
} // missing return in global function expected to return 'Bool'
func primeLength(string: String) -> Bool {
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
return false
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return false
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
return string.count.isPrime
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return string.count.isPrime
}
```
return string.count.isPrime // value of type 'Int' has no member 'isPrime'
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
return isPrime(number: length)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % 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
return isPrime(number: length)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let length = string.count
return isPrime(length)
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % 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
return isPrime(length)
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
```
return 10 * startsOneEnds(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let digits = String(i).count
if digits == n {
count += 1
} else if digits > n {
break
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let digits = String(i).count
if digits == n {
count += 1
} else if digits > n {
break
}
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
return 10 * (10 ^ (n - 1))
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
return 10 * (10 ^ (n - 1))
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
```
return 10 * startsOneEnds(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
```
return 10 * startsOneEnds(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
guard n > 0 else { return 0 }
var count = 0
for i in 1...n {
count += 10 * (10 ^ (i - 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 {
guard n > 0 else { return 0 }
var count = 0
for i in 1...n {
count += 10 * (10 ^ (i - 1))
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
let num = String(i)
if num.hasPrefix("1") || num.hasSuffix("1") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var result = ""
var num = N
while num > 0 {
result = String(num % 2) + result
num /= 2
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var result = ""
var num = N
while num > 0 {
result = String(num % 2) + result
num /= 2
}
return result
}
```
// 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)
}
```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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 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
}
```
if index % 2!= 0 && value % 2 == 0 { // expression is not assignable: binary operator returns immutable value
if index % 2!= 0 && value % 2 == 0 { // '=' must have consistent whitespace on both sides
if index % 2!= 0 && value % 2 == 0 { // use of '=' in a boolean context, did you mean '=='?
if index % 2!= 0 && value % 2 == 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if index % 2!= 0 && value % 2 == 0 { // cannot force unwrap value of non-optional type 'Int'
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 1 && 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 == 1 && value % 2 == 0 {
sum += value
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) { (result, element) -> Int in
if element.offset % 2 == 1 {
return result + element.element
}
return result
}
}
```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().reduce(0) { (result, element) -> Int in
if element.offset % 2 == 1 {
return result + element.element
}
return result
}
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 0? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 0? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 0? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 0? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
$0 + ($1.offset % 2 == 0? $1.element : 0) // expected ',' separator
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 0? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 0? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 0? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 0? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
$0 + ($1.offset % 2 == 0? $1.element : 0) // expected ',' separator
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) { $0 + ($1.offset % 2 == 0? $1.element : 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().reduce(0) { $0 + ($1.offset % 2 == 0? $1.element : 0) }
}
```
return lst.enumerated().reduce(0) { $0 + ($1.offset % 2 == 0? $1.element : 0) } // cannot use optional chaining on non-optional value of type 'Int'
return lst.enumerated().reduce(0) { $0 + ($1.offset % 2 == 0? $1.element : 0) } // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
return lst.enumerated().reduce(0) { $0 + ($1.offset % 2 == 0? $1.element : 0) } // expected ',' separator
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 0? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 0? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 0? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 0? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
$0 + ($1.offset % 2 == 0? $1.element : 0) // expected ',' separator
func add(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
$0.characters.sorted().reduce("", +)
}.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 {
return s.components(separatedBy: " ").map {
$0.characters.sorted().reduce("", +)
}.joined(separator: " ")
}
```
$0.characters.sorted().reduce("", +) // binary operator '+' cannot be applied to operands of type 'String' and 'String.Element' (aka 'Character')
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
String($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 {
return s.components(separatedBy: " ").map {
String($0.sorted())
}.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
$0.characters.sorted().reduce("", { $0 + String($1) })
}.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 {
return s.components(separatedBy: " ").map {
$0.characters.sorted().reduce("", { $0 + String($1) })
}.joined(separator: " ")
}
```
$0.characters.sorted().reduce("", { $0 + String($1) }) // 'characters' is unavailable: Please use String directly
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
$0.sorted(by: <).joined()
}.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 {
return s.components(separatedBy: " ").map {
$0.sorted(by: <).joined()
}.joined(separator: " ")
}
```
$0.sorted(by: <).joined() // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
$0.sorted(by: <).joined()
}.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 {
return s.components(separatedBy: " ").map {
$0.sorted(by: <).joined()
}.joined(separator: " ")
}
```
$0.sorted(by: <).joined() // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
$0.sorted(by: <)
}.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 {
return s.components(separatedBy: " ").map {
$0.sorted(by: <)
}.joined(separator: " ")
}
```
$0.sorted(by: <) // cannot convert value of type '[String.Element]' (aka 'Array<Character>') to closure result type 'String'
func antiShuffle(s: String) -> String {
return s.componentsSeparatedByString(" ").map {
var chars = Array($0.characters)
chars.sortInPlace { $0 < $1 }
return String(chars)
}.joinWithSeparator(" ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
return s.componentsSeparatedByString(" ").map {
var chars = Array($0.characters)
chars.sortInPlace { $0 < $1 }
return String(chars)
}.joinWithSeparator(" ")
}
```
return s.componentsSeparatedByString(" ").map { // value of type 'String' has no member 'componentsSeparatedByString'
chars.sortInPlace { $0 < $1 } // value of type 'Array<_>' has no member 'sortInPlace'
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map { $0.characters.sorted().reduce("", +) }.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 {
return s.components(separatedBy: " ").map { $0.characters.sorted().reduce("", +) }.joined(separator: " ")
}
```
return s.components(separatedBy: " ").map { $0.characters.sorted().reduce("", +) }.joined(separator: " ") // binary operator '+' cannot be applied to operands of type 'String' and 'String.Element' (aka 'Character')
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
var chars = [Character]()
for char in word {
chars.append(char)
}
chars.sort()
result += String(chars) + " "
}
return result
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
var chars = [Character]()
for char in word {
chars.append(char)
}
chars.sort()
result += String(chars) + " "
}
return result
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
return s.components(separatedBy: " ").map {
String($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 {
return s.components(separatedBy: " ").map {
String($0.sorted())
}.joined(separator: " ")
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort { $0.0 < $1.0 }
result.sort { $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)]()
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort { $0.0 < $1.0 }
result.sort { $0.1 > $1.1 }
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
var row = 0
var col = 0
var maxRow = lst.count - 1
var maxCol = lst[0].count - 1
while row <= maxRow && col <= maxCol {
if lst[row][col] == x {
result.append((row, col))
}
if lst[row][col] < x {
row += 1
} else {
col += 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
var col = 0
var maxRow = lst.count - 1
var maxCol = lst[0].count - 1
while row <= maxRow && col <= maxCol {
if lst[row][col] == x {
result.append((row, col))
}
if lst[row][col] < x {
row += 1
} else {
col += 1
}
}
return result
}
```
var maxRow = lst.count - 1 // variable 'maxRow' was never mutated; consider changing to 'let' constant
var maxCol = lst[0].count - 1 // variable 'maxCol' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort { (a, b) -> Bool in
if a.0 < b.0 {
return true
} else if a.0 == b.0 {
return a.1 > b.1
} else {
return false
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort { (a, b) -> Bool in
if a.0 < b.0 {
return true
} else if a.0 == b.0 {
return a.1 > b.1
} else {
return false
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
result.sort { $0.0 < $1.0 }
result.sort { $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)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
result.sort { $0.0 < $1.0 }
result.sort { $0.1 > $1.1 }
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
return lst.flatMap { $0.enumerated().filter { $0.element == x }.map { (row: $0.offset, column: $1) } }.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.flatMap { $0.enumerated().filter { $0.element == x }.map { (row: $0.offset, column: $1) } }.sorted { $0.0 < $1.0 }
}
```
return lst.flatMap { $0.enumerated().filter { $0.element == x }.map { (row: $0.offset, column: $1) } }.sorted { $0.0 < $1.0 } // value of type 'Int' has no member 'offset'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, element) in row.enumerated() {
if element == x {
result.append((i, j))
}
}
}
result.sort { (a, b) -> Bool in
if a.0 == b.0 {
return a.1 > b.1
} else {
return a.0 < b.0
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, element) in row.enumerated() {
if element == x {
result.append((i, j))
}
}
}
result.sort { (a, b) -> Bool in
if a.0 == b.0 {
return a.1 > b.1
} else {
return a.0 < b.0
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort { (a, b) -> Bool in
if a.0 < b.0 {
return true
} else if a.0 == b.0 {
return a.1 > b.1
} else {
return false
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort { (a, b) -> Bool in
if a.0 < b.0 {
return true
} else if a.0 == b.0 {
return a.1 > b.1
} else {
return false
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
result.sort { $0.0 < $1.0 }
result.sort { $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)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
result.sort { $0.0 < $1.0 }
result.sort { $0.1 > $1.1 }
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (index2, element) in row.enumerated() {
if element == x {
result.append((index, index2))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (index2, element) in row.enumerated() {
if element == x {
result.append((index, index2))
}
}
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var newArray = array
newArray.sort { $0 > $1 }
return newArray
}
```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 newArray = array
newArray.sort { $0 > $1 }
return newArray
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
return array.sorted { $0 + $1 % 2!= 0 }
}
```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] {
return array.sorted { $0 + $1 % 2!= 0 }
}
```
return array.sorted { $0 + $1 % 2!= 0 } // cannot convert value of type '()' to closure result type 'Bool'
return array.sorted { $0 + $1 % 2!= 0 } // expression is not assignable: binary operator returns immutable value
return array.sorted { $0 + $1 % 2!= 0 } // '=' must have consistent whitespace on both sides
return array.sorted { $0 + $1 % 2!= 0 } // cannot force unwrap value of non-optional type 'Int'
func sortArray(array: [Int]) -> [Int] {
return array.sorted { (a, b) -> Bool in
let sum = a + b
return sum % 2 == 0
}
}
```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] {
return array.sorted { (a, b) -> Bool in
let sum = a + b
return sum % 2 == 0
}
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
return array.sorted { $0 % 2 == 0 && $1 % 2 == 0? $0 > $1 : $0 % 2 == 0 }
}
```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] {
return array.sorted { $0 % 2 == 0 && $1 % 2 == 0? $0 > $1 : $0 % 2 == 0 }
}
```
return array.sorted { $0 % 2 == 0 && $1 % 2 == 0? $0 > $1 : $0 % 2 == 0 } // consecutive statements on a line must be separated by ';'
return array.sorted { $0 % 2 == 0 && $1 % 2 == 0? $0 > $1 : $0 % 2 == 0 } // consecutive statements on a line must be separated by ';'
return array.sorted { $0 % 2 == 0 && $1 % 2 == 0? $0 > $1 : $0 % 2 == 0 } // expected expression
return array.sorted { $0 % 2 == 0 && $1 % 2 == 0? $0 > $1 : $0 % 2 == 0 } // cannot use optional chaining on non-optional value of type 'Int'
func sortArray(array: [Int]) -> [Int] {
return array.sorted { $0 + $1 % 2!= 0 }
}
```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] {
return array.sorted { $0 + $1 % 2!= 0 }
}
```
return array.sorted { $0 + $1 % 2!= 0 } // cannot convert value of type '()' to closure result type 'Bool'
return array.sorted { $0 + $1 % 2!= 0 } // expression is not assignable: binary operator returns immutable value
return array.sorted { $0 + $1 % 2!= 0 } // '=' must have consistent whitespace on both sides
return array.sorted { $0 + $1 % 2!= 0 } // cannot force unwrap value of non-optional type 'Int'
func sortArray(array: [Int]) -> [Int] {
return array.sorted {
let sum = array.first! + array.last!
return sum % 2 == 0? $0 > $1 : $0 < $1
}
}
```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] {
return array.sorted {
let sum = array.first! + array.last!
return sum % 2 == 0? $0 > $1 : $0 < $1
}
}
```
return sum % 2 == 0? $0 > $1 : $0 < $1 // expected expression
return sum % 2 == 0? $0 > $1 : $0 < $1 // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? $0 > $1 : $0 < $1 // consecutive statements on a line must be separated by ';'
return sum % 2 == 0? $0 > $1 : $0 < $1 // cannot use optional chaining on non-optional value of type 'Int'
func sortArray(array: [Int]) -> [Int] {
return array.sorted {
let sum = $0 + $1
return sum % 2 == 0
}
}
```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] {
return array.sorted {
let sum = $0 + $1
return sum % 2 == 0
}
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
return array.sorted(by: { (a, b) -> Bool in
return (a + b) % 2 == 0
})
}
```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] {
return array.sorted(by: { (a, b) -> Bool in
return (a + b) % 2 == 0
})
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
result.sort { $0 < $1 }
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var result = array
result.sort { $0 < $1 }
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 }
}
```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] {
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 }
}
```
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 } // consecutive statements on a line must be separated by ';'
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 } // expected expression
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 } // consecutive statements on a line must be separated by ';'
return array.sorted { $0 % 2 == $1 % 2? $0 > $1 : $0 % 2 > $1 % 2 } // cannot use optional chaining on non-optional value of type 'Int'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let alphabetArray = Array(alphabet)
var newString = ""
for char in s {
let index = alphabetArray.firstIndex(of: String(char))
let newIndex = index! + 2
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)
var newString = ""
for char in s {
let index = alphabetArray.firstIndex(of: String(char))
let newIndex = index! + 2
let newChar = alphabetArray[newIndex]
newString.append(newChar)
}
return newString
}
encrypt(s: "hi")
encrypt(s: "asdfghjkl")
encrypt(s: "gf")
encrypt(s: "et")
```
let index = alphabetArray.firstIndex(of: String(char)) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
func encrypt(s: String) -> String {
return s
}
func decrypt(s: String) -> String {
return s
}
```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 {
return s
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
return s
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
return s
}
```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 {
return s
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = Int(char.asciiValue!)
let newAscii = ascii! + 2 * 2
let newChar = Character(UnicodeScalar(newAscii))
result.append(newChar)
}
return result
}
func decrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = Int(char.asciiValue!)
let newAscii = ascii! - 2 * 2
let newChar = Character(UnicodeScalar(newAscii))
result.append(newChar)
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = Int(char.asciiValue!)
let newAscii = ascii! + 2 * 2
let newChar = Character(UnicodeScalar(newAscii))
result.append(newChar)
}
return result
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = Int(char.asciiValue!)
let newAscii = ascii! - 2 * 2
let newChar = Character(UnicodeScalar(newAscii))
result.append(newChar)
}
return result
}
```
let newAscii = ascii! + 2 * 2 // cannot force unwrap value of non-optional type 'Int'
let newAscii = ascii! - 2 * 2 // cannot force unwrap value of non-optional type 'Int'
func encrypt(s: String) -> String {
return s
}
func decrypt(s: String) -> String {
return s
}
```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 {
return s
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
return s
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
return s
}
func decrypt(s: String) -> String {
return s
}
```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 {
return s
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
return s
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
return s
}
func decrypt(s: String) -> String {
return s
}
```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 {
return s
}
// Create a function decrypt that takes a string as an argument and
// returns a string decrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift up by two multiplied to two places.
// For example:
// decrypt(s: "lm") == "hi"
// decrypt(s: "ewhjklnop") == "asdfghjkl"
// decrypt(s: "kj") == "gf"
// decrypt(s: "ix") == "et"
func decrypt(s: String) -> String {
return s
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
return s
}
```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 {
return s
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
return ""
}
```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 {
return ""
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
// TODO: Write your code here
return nil
}
```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? {
// TODO: Write your code here
return nil
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
// Write your code here
var min = lst[0]
var min2 = lst[0]
for i in 1..<lst.count {
if lst[i] < min {
min2 = min
min = lst[i]
} else if lst[i] < min2 {
min2 = lst[i]
}
}
return min2 == min? nil : min2
}
```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? {
// Write your code here
var min = lst[0]
var min2 = lst[0]
for i in 1..<lst.count {
if lst[i] < min {
min2 = min
min = lst[i]
} else if lst[i] < min2 {
min2 = lst[i]
}
}
return min2 == min? nil : min2
}
```
return min2 == min? nil : min2 // expected expression
return min2 == min? nil : min2 // cannot convert return expression of type 'Bool' to return type 'Int?'
return min2 == min? nil : min2 // consecutive statements on a line must be separated by ';'
return min2 == min? nil : min2 // cannot use optional chaining on non-optional value of type 'Int'
return min2 == min? nil : min2 // consecutive statements on a line must be separated by ';'
return min2 == min? nil : min2 // 'nil' requires a contextual type
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var min = lst[0]
var minIndex = 0
for (i, num) in lst.enumerated() {
if num < min {
min = num
minIndex = i
}
}
var min2 = lst[0]
for (i, num) in lst.enumerated() {
if num < min2 && i!= minIndex {
min2 = num
}
}
return min2
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var min = lst[0]
var minIndex = 0
for (i, num) in lst.enumerated() {
if num < min {
min = num
minIndex = i
}
}
var min2 = lst[0]
for (i, num) in lst.enumerated() {
if num < min2 && i!= minIndex {
min2 = num
}
}
return min2
}
```
if num < min2 && i!= minIndex { // '=' must have consistent whitespace on both sides
if num < min2 && i!= minIndex { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num < min2 && i!= minIndex { // cannot force unwrap value of non-optional type 'Int'
if num < min2 && i!= minIndex { // use of '=' in a boolean context, did you mean '=='?
func nextSmallest(lst: [Int]) -> Int? {
// Write your code here
}
```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? {
// Write your code here
}
```
} // missing return in global function expected to return 'Int?'
func nextSmallest(lst: [Int]) -> Int? {
return lst.sorted().dropFirst().first
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
return lst.sorted().dropFirst().first
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
// TODO: Write your code here
return nil
}
```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? {
// TODO: Write your code here
return nil
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
var smallest = lst[0]
var secondSmallest = lst[0]
for i in 1..<lst.count {
if lst[i] < smallest {
secondSmallest = smallest
smallest = lst[i]
} else if lst[i] < secondSmallest {
secondSmallest = lst[i]
}
}
return secondSmallest
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var bored = 0
let sentences = S.components(separatedBy: CharacterSet(charactersIn: ".?!") )
for sentence in sentences {
if sentence.hasPrefix("I") {
bored += 1
}
}
return bored
}
```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 bored = 0
let sentences = S.components(separatedBy: CharacterSet(charactersIn: ".?!") )
for sentence in sentences {
if sentence.hasPrefix("I") {
bored += 1
}
}
return bored
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".!?").filter {!$0.isEmpty }
return words.filter { $0.hasPrefix("I") }.count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".!?").filter {!$0.isEmpty }
return words.filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: ".!?").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.components(separatedBy: ".!?").filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: ".!?").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.components(separatedBy: ".!?").filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: ".!?").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.components(separatedBy: ".!?").filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var boredom = 0
for word in S.components(separatedBy: " ") {
if word.hasPrefix("I") {
boredom += 1
}
}
return boredom
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var boredom = 0
for word in S.components(separatedBy: " ") {
if word.hasPrefix("I") {
boredom += 1
}
}
return boredom
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: ".!?").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.components(separatedBy: ".!?").filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: ".!?").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.components(separatedBy: ".!?").filter { $0.hasPrefix("I") }.count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var bored = 0
var sentence = ""
for char in S {
if char == " " {
if sentence.hasPrefix("I") {
bored += 1
}
sentence = ""
} else {
sentence.append(char)
}
}
if sentence.hasPrefix("I") {
bored += 1
}
return bored
}
```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 bored = 0
var sentence = ""
for char in S {
if char == " " {
if sentence.hasPrefix("I") {
bored += 1
}
sentence = ""
} else {
sentence.append(char)
}
}
if sentence.hasPrefix("I") {
bored += 1
}
return bored
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.components(separatedBy: ".!?").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.components(separatedBy: ".!?").filter({$0.hasPrefix("I")}).count
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil
}
```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 || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil
}
```
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // 'nil' cannot be assigned to type 'Bool'
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // no exact matches in call to initializer
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // no exact matches in call to initializer
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // 'nil' is not compatible with expected argument type 'Bool'
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // 'nil' is not compatible with expected argument type 'Bool'
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // no exact matches in call to initializer
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // '=' must have consistent whitespace on both sides
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // '=' must have consistent whitespace on both sides
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // expression is not assignable: '&&' returns immutable value
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // expression is not assignable: '&&' returns immutable value
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // expression is not assignable: '&&' returns immutable value
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // use of '=' in a boolean context, did you mean '=='?
return (x == y + z || y == x + z || z == x + y) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // '=' must have consistent whitespace on both sides
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil
}
```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) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil
}
```
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // no exact matches in call to initializer
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // expression is not assignable: '&&' returns immutable value
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // 'nil' is not compatible with expected argument type 'Bool'
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // '=' must have consistent whitespace on both sides
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // 'nil' cannot be assigned to type 'Bool'
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // expression is not assignable: '&&' returns immutable value
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // use of '=' in a boolean context, did you mean '=='?
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // '=' must have consistent whitespace on both sides
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // no exact matches in call to initializer
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // 'nil' is not compatible with expected argument type 'Bool'
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // no exact matches in call to initializer
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // '=' must have consistent whitespace on both sides
return (x + y == z || x + z == y || y + z == x) && Int(x)!= nil && Int(y)!= nil && Int(z)!= nil // expression is not assignable: '&&' returns immutable value
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```
// 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 {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z || y == x + z || z == x + y) && (x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0)
}
```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 || y == x + z || z == x + y) && (x.truncatingRemainder(dividingBy: 1) == 0 && y.truncatingRemainder(dividingBy: 1) == 0 && z.truncatingRemainder(dividingBy: 1) == 0)
}
```
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (x == y + z) || (y == x + z) || (z == x + y)
}
```
// 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 {
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 encode(message: String) -> String {
return message.map {
if $0.isVowel {
return $0.nextVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var nextVowel: Character {
return "aeiou".dropFirst(2).first?? "a"
}
}
```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 {
return message.map {
if $0.isVowel {
return $0.nextVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var nextVowel: Character {
return "aeiou".dropFirst(2).first?? "a"
}
}
```
return $0.nextVowel // cannot convert value of type 'Character' to closure result type 'String'
return "aeiou".dropFirst(2).first?? "a" // value of optional type 'Substring.Element?' (aka 'Optional<Character>') must be unwrapped to a value of type 'Substring.Element' (aka 'Character')
return "aeiou".dropFirst(2).first?? "a" // consecutive statements on a line must be separated by ';'
return "aeiou".dropFirst(2).first?? "a" // cannot use optional chaining on non-optional value of type 'Substring.Element' (aka 'Character')
return "aeiou".dropFirst(2).first?? "a" // string literal is unused
func encode(message: String) -> String {
return message.map {
if $0.isVowel {
return $0.nextVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var nextVowel: Character {
let vowels = "aeiou"
let index = vowels.firstIndex(of: self)!
let nextIndex = index + 2
return vowels[vowels.index(vowels.startIndex, offsetBy: nextIndex)]
}
}
```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 {
return message.map {
if $0.isVowel {
return $0.nextVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var nextVowel: Character {
let vowels = "aeiou"
let index = vowels.firstIndex(of: self)!
let nextIndex = index + 2
return vowels[vowels.index(vowels.startIndex, offsetBy: nextIndex)]
}
}
```
return $0.nextVowel // cannot convert value of type 'Character' to closure result type 'String'
let nextIndex = index + 2 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encode(message: String) -> String {
return message.map {
if $0.isVowel {
return $0.swapCasedVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var swapCasedVowel: Character {
let vowels = "aeiou"
let vowelIndex = vowels.firstIndex(of: self)!
let newVowelIndex = vowelIndex + 2
let newVowel = vowels[newVowelIndex]
return newVowel
}
}
```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 {
return message.map {
if $0.isVowel {
return $0.swapCasedVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var swapCasedVowel: Character {
let vowels = "aeiou"
let vowelIndex = vowels.firstIndex(of: self)!
let newVowelIndex = vowelIndex + 2
let newVowel = vowels[newVowelIndex]
return newVowel
}
}
```
return $0.swapCasedVowel // cannot convert value of type 'Character' to closure result type 'String'
let newVowelIndex = vowelIndex + 2 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char.isVowel {
newMessage += char.swapCase()
} else {
newMessage += char
}
}
return newMessage
}
extension Character {
var isVowel: Bool {
switch self {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
func swapCase() -> Character {
switch self {
case self.lowercased():
return self.uppercased()
case self.uppercased():
return self.lowercased()
default:
return self
}
}
}
```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.isVowel {
newMessage += char.swapCase()
} else {
newMessage += char
}
}
return newMessage
}
extension Character {
var isVowel: Bool {
switch self {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
func swapCase() -> Character {
switch self {
case self.lowercased():
return self.uppercased()
case self.uppercased():
return self.lowercased()
default:
return self
}
}
}
```
newMessage += char.swapCase() // cannot convert value of type 'Character' to expected argument type 'String'
newMessage += char // cannot convert value of type 'Character' to expected argument type 'String'
case self.lowercased(): // expression pattern of type 'String' cannot match values of type 'Character'
return self.uppercased() // cannot convert return expression of type 'String' to return type 'Character'
case self.uppercased(): // expression pattern of type 'String' cannot match values of type 'Character'
return self.lowercased() // cannot convert return expression of type 'String' to return type 'Character'
func encode(message: String) -> String {
let vowels = "aeiou"
var newMessage = ""
for char in message {
if vowels.contains(char) {
let index = vowels.index(of: char)
let newIndex = vowels.index(index!, offsetBy: 2)
newMessage += String(vowels[newIndex!])
} 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 = "aeiou"
var newMessage = ""
for char in message {
if vowels.contains(char) {
let index = vowels.index(of: char)
let newIndex = vowels.index(index!, offsetBy: 2)
newMessage += String(vowels[newIndex!])
} else {
newMessage += String(char).uppercased()
}
}
return newMessage
}
```
let index = vowels.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
newMessage += String(vowels[newIndex!]) // cannot force unwrap value of non-optional type 'String.Index'
func encode(message: String) -> String {
return message.map {
if $0.isVowel {
return $0.swapCasedVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var swapCasedVowel: Character {
let vowels = "aeiou"
let vowelIndex = vowels.firstIndex(of: self)!
let nextVowel = vowels.index(vowelIndex, offsetBy: 2)
return vowels[nextVowel]
}
}
```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 {
return message.map {
if $0.isVowel {
return $0.swapCasedVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var swapCasedVowel: Character {
let vowels = "aeiou"
let vowelIndex = vowels.firstIndex(of: self)!
let nextVowel = vowels.index(vowelIndex, offsetBy: 2)
return vowels[nextVowel]
}
}
```
return $0.swapCasedVowel // cannot convert value of type 'Character' to closure result type 'String'
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char.isVowel {
newMessage += char.swapCase.advance(2)
} else {
newMessage += char.swapCase
}
}
return newMessage
}
extension Character {
var isVowel: Bool {
switch self {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
var swapCase: Character {
if isUppercase {
return Character(String(lowercased()))
} else {
return Character(String(uppercased()))
}
}
}
```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.isVowel {
newMessage += char.swapCase.advance(2)
} else {
newMessage += char.swapCase
}
}
return newMessage
}
extension Character {
var isVowel: Bool {
switch self {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
var swapCase: Character {
if isUppercase {
return Character(String(lowercased()))
} else {
return Character(String(uppercased()))
}
}
}
```
newMessage += char.swapCase.advance(2) // value of type 'Character' has no member 'advance'
newMessage += char.swapCase // cannot convert value of type 'Character' to expected argument type 'String'
func encode(message: String) -> String {
return message.map {
if $0.isVowel {
return $0.nextVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
switch self {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
var nextVowel: Character {
switch self {
case "a":
return "e"
case "e":
return "i"
case "i":
return "o"
case "o":
return "u"
case "u":
return "a"
default:
return self
}
}
}
```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 {
return message.map {
if $0.isVowel {
return $0.nextVowel
} else {
return $0
}
}.joined()
}
extension Character {
var isVowel: Bool {
switch self {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
var nextVowel: Character {
switch self {
case "a":
return "e"
case "e":
return "i"
case "i":
return "o"
case "o":
return "u"
case "u":
return "a"
default:
return self
}
}
}
```
return $0.nextVowel // cannot convert value of type 'Character' to closure result type 'String'
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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
// XCTAssertTrue failed
func encode(message: String) -> String {
return message.map {
if $0.isVowel {
return $0.nextVowel
}
return $0
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var nextVowel: Character {
let vowels = "aeiou"
let index = vowels.firstIndex(of: self)!
let nextIndex = index + 2
return vowels[vowels.index(vowels.startIndex, offsetBy: nextIndex)]
}
}
```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 {
return message.map {
if $0.isVowel {
return $0.nextVowel
}
return $0
}.joined()
}
extension Character {
var isVowel: Bool {
return "aeiou".contains(self)
}
var nextVowel: Character {
let vowels = "aeiou"
let index = vowels.firstIndex(of: self)!
let nextIndex = index + 2
return vowels[vowels.index(vowels.startIndex, offsetBy: nextIndex)]
}
}
```
return $0.nextVowel // cannot convert value of type 'Character' to closure result type 'String'
let nextIndex = index + 2 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigits = 0
for i in lst {
if i > 0 {
var isPrime = true
for j in 2...i/2 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
var digits = 0
var num = i
while num > 0 {
digits += 1
num /= 10
}
if digits > maxPrimeDigits {
maxPrime = i
maxPrimeDigits = digits
}
}
}
}
return maxPrime
}
```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 maxPrimeDigits = 0
for i in lst {
if i > 0 {
var isPrime = true
for j in 2...i/2 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
var digits = 0
var num = i
while num > 0 {
digits += 1
num /= 10
}
if digits > maxPrimeDigits {
maxPrime = i
maxPrimeDigits = digits
}
}
}
}
return maxPrime
}
```
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var sum = 0
for i in lst {
if isPrime(i) {
if i > maxPrime {
maxPrime = i
}
}
}
while maxPrime > 0 {
sum += maxPrime % 10
maxPrime /= 10
}
return sum
}
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 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 i in lst {
if isPrime(i) {
if i > maxPrime {
maxPrime = i
}
}
}
while maxPrime > 0 {
sum += maxPrime % 10
maxPrime /= 10
}
return sum
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
var largestPrimeSum = 0
for i in lst {
if isPrime(num: i) {
if i > largestPrime {
largestPrime = i
largestPrimeSum = sumOfDigits(num: largestPrime)
}
}
}
return largestPrimeSum
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
if num == 2 {
return true
}
if num % 2 == 0 {
return false
}
for i in 3...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var numCopy = num
while numCopy > 0 {
sum += numCopy % 10
numCopy /= 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
var largestPrimeSum = 0
for i in lst {
if isPrime(num: i) {
if i > largestPrime {
largestPrime = i
largestPrimeSum = sumOfDigits(num: largestPrime)
}
}
}
return largestPrimeSum
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
if num == 2 {
return true
}
if num % 2 == 0 {
return false
}
for i in 3...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var numCopy = num
while numCopy > 0 {
sum += numCopy % 10
numCopy /= 10
}
return sum
}
```
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeSum = 0
for num in lst {
if isPrime(num) {
if num > maxPrime {
maxPrime = num
maxPrimeSum = sumOfDigits(num)
}
}
}
return maxPrimeSum
}
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 maxPrime = 0
var maxPrimeSum = 0
for num in lst {
if isPrime(num) {
if num > maxPrime {
maxPrime = num
maxPrimeSum = sumOfDigits(num)
}
}
}
return maxPrimeSum
}
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 maxPrimeDigits = 0
for number in lst {
if number > 0 {
var isPrime = true
for i in 2..<number {
if number % i == 0 {
isPrime = false
break
}
}
if isPrime {
var primeDigits = 0
var temp = number
while temp > 0 {
primeDigits += temp % 10
temp /= 10
}
if primeDigits > maxPrimeDigits {
maxPrime = number
maxPrimeDigits = primeDigits
}
}
}
}
return maxPrimeDigits
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigits = 0
for number in lst {
if number > 0 {
var isPrime = true
for i in 2..<number {
if number % i == 0 {
isPrime = false
break
}
}
if isPrime {
var primeDigits = 0
var temp = number
while temp > 0 {
primeDigits += temp % 10
temp /= 10
}
if primeDigits > maxPrimeDigits {
maxPrime = number
maxPrimeDigits = primeDigits
}
}
}
}
return maxPrimeDigits
}
```
var maxPrime = 0 // variable 'maxPrime' was written to, but never read
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeDigits = 0
for i in lst {
if i > 0 {
var isPrime = true
for j in 2...i/2 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
var digits = 0
var temp = i
while temp > 0 {
temp /= 10
digits += 1
}
if digits > maxPrimeDigits {
maxPrime = i
maxPrimeDigits = digits
}
}
}
}
return maxPrime
}
```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 maxPrimeDigits = 0
for i in lst {
if i > 0 {
var isPrime = true
for j in 2...i/2 {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
var digits = 0
var temp = i
while temp > 0 {
temp /= 10
digits += 1
}
if digits > maxPrimeDigits {
maxPrime = i
maxPrimeDigits = digits
}
}
}
}
return maxPrime
}
```
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeSum = 0
for num in lst {
if num == 0 {
continue
}
var isPrime = true
for i in 2..<num {
if num % i == 0 {
isPrime = false
break
}
}
if isPrime {
maxPrime = num
maxPrimeSum = 0
for digit in String(num) {
maxPrimeSum += Int(String(digit))!
}
}
}
return maxPrimeSum
}
```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 maxPrimeSum = 0
for num in lst {
if num == 0 {
continue
}
var isPrime = true
for i in 2..<num {
if num % i == 0 {
isPrime = false
break
}
}
if isPrime {
maxPrime = num
maxPrimeSum = 0
for digit in String(num) {
maxPrimeSum += Int(String(digit))!
}
}
}
return maxPrimeSum
}
```
var maxPrime = 0 // variable 'maxPrime' was written to, but never read
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeSum = 0
for i in lst {
if isPrime(i) {
maxPrime = i
maxPrimeSum = sumOfDigits(i)
break
}
}
for i in lst {
if isPrime(i) && sumOfDigits(i) > maxPrimeSum {
maxPrime = i
maxPrimeSum = sumOfDigits(i)
}
}
return maxPrimeSum
}
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
}
func sumOfDigits(_ n: Int) -> Int {
var sum = 0
for i in String(n) {
sum += Int(String(i))!
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeSum = 0
for i in lst {
if isPrime(i) {
maxPrime = i
maxPrimeSum = sumOfDigits(i)
break
}
}
for i in lst {
if isPrime(i) && sumOfDigits(i) > maxPrimeSum {
maxPrime = i
maxPrimeSum = sumOfDigits(i)
}
}
return maxPrimeSum
}
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
}
func sumOfDigits(_ n: Int) -> Int {
var sum = 0
for i in String(n) {
sum += Int(String(i))!
}
return sum
}
```
var maxPrime = 0 // variable 'maxPrime' was written to, but never read
// Fatal error: Range requires lowerBound <= upperBound
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
maxPrime = max(maxPrime, i)
}
}
}
while maxPrime > 0 {
sum += maxPrime % 10
maxPrime /= 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 sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
maxPrime = max(maxPrime, i)
}
}
}
while maxPrime > 0 {
sum += maxPrime % 10
maxPrime /= 10
}
return sum
}
```
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
var largestPrimeSum = 0
for num in lst {
if num > 0 {
var isPrime = true
for i in 2...num/2 {
if num % i == 0 {
isPrime = false
break
}
}
if isPrime {
largestPrime = num
largestPrimeSum = 0
for digit in String(num) {
largestPrimeSum += Int(String(digit))!
}
break
}
}
}
return largestPrimeSum
}
```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 largestPrimeSum = 0
for num in lst {
if num > 0 {
var isPrime = true
for i in 2...num/2 {
if num % i == 0 {
isPrime = false
break
}
}
if isPrime {
largestPrime = num
largestPrimeSum = 0
for digit in String(num) {
largestPrimeSum += Int(String(digit))!
}
break
}
}
}
return largestPrimeSum
}
```
var largestPrime = 0 // variable 'largestPrime' was written to, but never read
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
var count = 2
while count < n {
if isPrime(number: count) {
primeNumbers.append(count)
}
count += 1
}
return primeNumbers
}
func isPrime(number: Int) -> Bool {
var isPrime = true
var count = 2
while count < number {
if number % count == 0 {
isPrime = false
}
count += 1
}
return isPrime
}
```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 primeNumbers = [Int]()
var count = 2
while count < n {
if isPrime(number: count) {
primeNumbers.append(count)
}
count += 1
}
return primeNumbers
}
func isPrime(number: Int) -> Bool {
var isPrime = true
var count = 2
while count < number {
if number % count == 0 {
isPrime = false
}
count += 1
}
return 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
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
guard n!= 2 else { return true }
guard n!= 3 else { return true }
guard n!= 5 else { return true }
guard n!= 7 else { return true }
guard n!= 11 else { return true }
guard n!= 13 else { return true }
guard n!= 17 else { return true }
guard n!= 19 else { return true }
guard n!= 23 else { return true }
guard n!= 29 else { return true }
guard n!= 31 else { return true }
guard n!= 37 else { return true }
guard n!= 41 else { return true }
guard n!= 43 else { return true }
guard n!= 47 else { return true }
guard n!= 53 else { return true }
guard n!= 59 else { return true }
guard n!= 61 else { return true }
guard n!= 67 else { return true }
guard n!= 71 else { return true }
guard n!= 73 else { return true }
guard n!= 79 else { return true }
guard n!= 83 else { return true }
guard n!= 89 else { return true }
guard n!= 97 else { return true }
guard n!= 101 else { return true }
guard n!= 103 else { return true }
guard n!= 107 else { return true }
guard n!= 109 else { return true }
guard n!= 113 else { return true }
guard n!= 127 else { return true }
guard n!= 131 else { return true }
guard n!= 137 else { return true }
guard n!= 139 else { return true }
guard n!= 149 else { return true }
guard n!= 151 else { return true }
guard n!= 157 else { return true }
guard n!= 163 else { return true }
guard n!= 167 else { return true }
guard n!= 173 else { return true }
guard n!= 179 else { return true }
guard n!= 181 else { return true }
guard n!= 191 else { return true }
guard n!= 193 else { return true }
guard n!= 197 else { return true }
guard n!= 199 else { return true }
guard n!= 211 else { return true }
guard n!= 223 else { return true }
guard n!= 227 else { return true }
guard n!= 229 else { return true }
guard n!= 233 else { return true }
guard n!= 239 else { return true }
guard n!= 241 else { return true }
guard n!= 251 else { return true }
guard n!= 257 else { return true }
guard n!= 263 else { return true }
guard n!= 269 else { return true }
guard n!= 271 else { return true }
guard n!= 277 else { return true }
guard n!= 281 else { return true }
guard n!= 283 else { return true }
guard n!= 293 else { return true }
guard n!= 307 else { return true }
guard n!= 311 else { return true }
guard n!= 313 else { return true }
guard n!= 317 else { return true }
guard n!= 331 else { return true }
guard n!= 337 else { return true }
guard n!= 347 else { return true }
guard n!= 349 else { return true }
guard n!= 353 else { return true }
guard n!= 359 else { return true }
guard n!= 367 else { return true }
guard n!= 373 else { return true }
guard n!= 379 else { return true }
guard n!= 383 else { return
if isPrime(i) { // cannot find 'isPrime' in scope
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(n: i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(n: i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
countUpTo(n: 5)
countUpTo(n: 11)
countUpTo(n: 0)
countUpTo(n: 20)
countUpTo(n: 1)
countUpTo(n: 18)
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
for i in 2...n {
if isPrime(i) {
primeNumbers.append(i)
}
}
return primeNumbers
}
func isPrime(_ n: Int) -> Bool {
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
for i in 2...n {
if isPrime(i) {
primeNumbers.append(i)
}
}
return primeNumbers
}
func isPrime(_ n: Int) -> Bool {
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
countUpTo(n: 5)
countUpTo(n: 11)
countUpTo(n: 0)
countUpTo(n: 20)
countUpTo(n: 1)
countUpTo(n: 18)
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(n: i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(n: i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var count = 2
while result.count < n {
if isPrime(count) {
result.append(count)
}
count += 1
}
return result
}
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
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var count = 2
while result.count < n {
if isPrime(count) {
result.append(count)
}
count += 1
}
return result
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
for i in 2...n {
if isPrime(i) {
primeNumbers.append(i)
}
}
return primeNumbers
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
for i in 2...n {
if isPrime(i) {
primeNumbers.append(i)
}
}
return primeNumbers
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
countUpTo(n: 5)
countUpTo(n: 11)
countUpTo(n: 0)
countUpTo(n: 20)
countUpTo(n: 1)
countUpTo(n: 18)
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
for i in 2...n {
if isPrime(i) {
primeNumbers.append(i)
}
}
return primeNumbers
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primeNumbers = [Int]()
for i in 2...n {
if isPrime(i) {
primeNumbers.append(i)
}
}
return primeNumbers
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func multiply(a: Int, b: Int) -> Int {
return abs(a % 10) * abs(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 abs(a % 10) * abs(b % 10)
}
```
func multiply(a: Int, b: Int) -> Int {
return abs(a % 10) * abs(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 abs(a % 10) * abs(b % 10)
}
```
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 abs(a % 10) * abs(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 abs(a % 10) * abs(b % 10)
}
```
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 abs(a) * abs(b)
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return abs(a) * abs(b)
}
```
// 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 abs(a % 10) * abs(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 abs(a % 10) * abs(b % 10)
}
```
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 abs(a % 10) * abs(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 abs(a % 10) * abs(b % 10)
}
```
func countUpper(s: String) -> Int {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```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 {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot convert value of type '(Bool?, Int)' to expected argument type 'Int'
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // expected ',' separator
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot use optional chaining on non-optional value of type 'Bool'
func countUpper(s: String) -> Int {
return s.filter { $0.isUpper }.count / 2
}
```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 {
return s.filter { $0.isUpper }.count / 2
}
```
return s.filter { $0.isUpper }.count / 2 // value of type 'String.Element' (aka 'Character') has no member 'isUpper'
func countUpper(s: String) -> Int {
return s.reduce(0) {
$0 + ($1.isUpper()? 1 : 0)
}
}
```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 {
return s.reduce(0) {
$0 + ($1.isUpper()? 1 : 0)
}
}
```
$0 + ($1.isUpper()? 1 : 0) // value of type 'String.Element' (aka 'Character') has no member 'isUpper'
$0 + ($1.isUpper()? 1 : 0) // cannot convert value of type '(Optional<_>, Int)' to expected argument type 'Int'
$0 + ($1.isUpper()? 1 : 0) // expected ',' separator
func countUpper(s: String) -> Int {
return s.reduce(0) {
if $0.isUppercase {
return $0 + 1
}
return $0
}
}
```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 {
return s.reduce(0) {
if $0.isUppercase {
return $0 + 1
}
return $0
}
}
```
return s.reduce(0) { // contextual closure type '(Int, String.Element) throws -> Int' (aka '(Int, Character) throws -> Int') expects 2 arguments, but 1 was used in closure body
if $0.isUppercase { // value of type 'Int' has no member 'isUppercase'
func countUpper(s: String) -> Int {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```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 {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot convert value of type '(Bool?, Int)' to expected argument type 'Int'
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // expected ',' separator
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot use optional chaining on non-optional value of type 'Bool'
func countUpper(s: String) -> Int {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```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 {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot convert value of type '(Bool?, Int)' to expected argument type 'Int'
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // expected ',' separator
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot use optional chaining on non-optional value of type 'Bool'
func countUpper(s: String) -> Int {
return s.filter { $0.isUpper }.count / 2
}
```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 {
return s.filter { $0.isUpper }.count / 2
}
```
return s.filter { $0.isUpper }.count / 2 // value of type 'String.Element' (aka 'Character') has no member 'isUpper'
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if i % 2 == 0 {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if i % 2 == 0 {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
}
return count
}
```
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```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 {
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) }
}
```
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot convert value of type '(Bool?, Int)' to expected argument type 'Int'
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // expected ',' separator
return s.reduce(0) { $0 + ($1.isUppercase? 1 : 0) } // cannot use optional chaining on non-optional value of type 'Bool'
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if i % 2 == 0 {
if c.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 (i, c) in s.enumerated() {
if i % 2 == 0 {
if c.isUppercase {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let closest = Int(round(number))
let distance = abs(closest - number)
let distanceFromZero = abs(closest)
if distance < distanceFromZero {
return closest
} else {
return closest * -1
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)?? 0
let closest = Int(round(number))
let distance = abs(closest - number)
let distanceFromZero = abs(closest)
if distance < distanceFromZero {
return closest
} else {
return closest * -1
}
}
```
let number = Double(value)?? 0 // integer literal is unused
let number = Double(value)?? 0 // consecutive statements on a line must be separated by ';'
let number = Double(value)?? 0 // cannot use optional chaining on non-optional value of type 'Double'
let distance = abs(closest - number) // cannot convert value of type 'Duration' to expected argument type 'Int32'
func closestInteger(value: String) -> Int {
return Int(value)?? 0
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
return Int(value)?? 0
}
```
return Int(value)?? 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return Int(value)?? 0 // cannot use optional chaining on non-optional value of type 'Int'
return Int(value)?? 0 // consecutive statements on a line must be separated by ';'
return Int(value)?? 0 // integer literal is unused
func closestInteger(value: String) -> Int {
return Int(value)!
}
```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 {
return Int(value)!
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func closestInteger(value: String) -> Int {
return 0
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
return 0
}
```
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
return Int(round(Double(value)!))
}
```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 {
return Int(round(Double(value)!))
}
```
func closestInteger(value: String) -> Int {
return Int(value)!
}
```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 {
return Int(value)!
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func closestInteger(value: String) -> Int {
return Int(round(Double(value)!))
}
```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 {
return Int(round(Double(value)!))
}
```
func closestInteger(value: String) -> Int {
return Int(round(Double(value)!))
}
```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 {
return Int(round(Double(value)!))
}
```
func closestInteger(value: String) -> Int {
return Int(round(Double(value)!))
}
```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 {
return Int(round(Double(value)!))
}
```
func closestInteger(value: String) -> Int {
return 0
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
return 0
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
while stones > 0 {
result.append(stones)
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 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 stones = n
while stones > 0 {
result.append(stones)
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2
}
return result
}
```
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // expected expression
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // result of operator '/' is unused
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // cannot assign value of type 'Bool' to type 'Int'
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = 1
var level = 1
while stones <= n {
result.append(stones)
stones += level
level += 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 stones = 1
var level = 1
while stones <= n {
result.append(stones)
stones += level
level += 1
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
while stones > 0 {
result.append(stones)
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 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 stones = n
while stones > 0 {
result.append(stones)
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2
}
return result
}
```
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2 // expected expression
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2 // cannot use optional chaining on non-optional value of type 'Bool'
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2 // result of operator '/' is unused
stones = (stones % 2 == 0)? stones / 2 : (stones + 1) / 2 // cannot assign value of type 'Bool?' to type 'Int'
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
var level = 1
while stones > 0 {
result.append(stones)
stones = (level % 2 == 0)? (level + 1) : (level + 2)
level += 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 stones = n
var level = 1
while stones > 0 {
result.append(stones)
stones = (level % 2 == 0)? (level + 1) : (level + 2)
level += 1
}
return result
}
```
stones = (level % 2 == 0)? (level + 1) : (level + 2) // cannot call value of non-function type 'Bool'
stones = (level % 2 == 0)? (level + 1) : (level + 2) // consecutive statements on a line must be separated by ';'
stones = (level % 2 == 0)? (level + 1) : (level + 2) // cannot assign value of type 'Optional<_>' to type 'Int'
stones = (level % 2 == 0)? (level + 1) : (level + 2) // cannot use optional chaining on non-optional value of type 'Bool'
stones = (level % 2 == 0)? (level + 1) : (level + 2) // expected expression
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
while stones > 0 {
result.append(stones)
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 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 stones = n
while stones > 0 {
result.append(stones)
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2
}
return result
}
```
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // expected expression
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // result of operator '/' is unused
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // cannot assign value of type 'Bool' to type 'Int'
func makeAPile(n: Int) -> [Int] {
return (0..<n).map {
let next = $0 % 2 == 0? $0 + 1 : $0 + 2
return next
}
}
```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] {
return (0..<n).map {
let next = $0 % 2 == 0? $0 + 1 : $0 + 2
return next
}
}
```
let next = $0 % 2 == 0? $0 + 1 : $0 + 2 // cannot use optional chaining on non-optional value of type 'Int'
let next = $0 % 2 == 0? $0 + 1 : $0 + 2 // expected expression
let next = $0 % 2 == 0? $0 + 1 : $0 + 2 // consecutive statements on a line must be separated by ';'
let next = $0 % 2 == 0? $0 + 1 : $0 + 2 // consecutive statements on a line must be separated by ';'
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
var level = 1
while stones > 0 {
result.append(stones)
stones = (level % 2 == 0)? stones + 1 : stones + 2
level += 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 stones = n
var level = 1
while stones > 0 {
result.append(stones)
stones = (level % 2 == 0)? stones + 1 : stones + 2
level += 1
}
return result
}
```
stones = (level % 2 == 0)? stones + 1 : stones + 2 // consecutive statements on a line must be separated by ';'
stones = (level % 2 == 0)? stones + 1 : stones + 2 // expected expression
stones = (level % 2 == 0)? stones + 1 : stones + 2 // cannot assign value of type 'Bool?' to type 'Int'
stones = (level % 2 == 0)? stones + 1 : stones + 2 // result of operator '+' is unused
stones = (level % 2 == 0)? stones + 1 : stones + 2 // cannot use optional chaining on non-optional value of type 'Bool'
stones = (level % 2 == 0)? stones + 1 : stones + 2 // consecutive statements on a line must be separated by ';'
func makeAPile(n: Int) -> [Int] {
return (1...n).map { $0 * 2 - 1 }
}
```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] {
return (1...n).map { $0 * 2 - 1 }
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
while stones > 0 {
result.append(stones)
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 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 stones = n
while stones > 0 {
result.append(stones)
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2
}
return result
}
```
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // cannot assign value of type 'Bool' to type 'Int'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // cannot use optional chaining on non-optional value of type 'Int'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // expected expression
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // consecutive statements on a line must be separated by ';'
stones = stones % 2 == 0? stones / 2 : (stones + 1) / 2 // result of operator '/' is unused
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var stones = n
while stones > 0 {
result.append(stones)
stones = (stones &+ 1) &- 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 stones = n
while stones > 0 {
result.append(stones)
stones = (stones &+ 1) &- 1
}
return result
}
```
func wordsString(s: String) -> [String] {
return s.componentsSeparatedByString(", ")
}
```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.componentsSeparatedByString(", ")
}
```
return s.componentsSeparatedByString(", ") // value of type 'String' has no member 'componentsSeparatedByString'
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ", ")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.components(separatedBy: ",")
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
// Write your code here
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
// Write your code here
}
```
} // missing return in global function expected to return 'Int'
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
// Write your code here
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
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 {
// Write your code here
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
break
}
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
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 {
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 avg = (Double(n) + Double(m)) / 2
return.success(String(avg.rounded(), 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) + Double(m)) / 2
return.success(String(avg.rounded(), radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return.success(String(avg.rounded(), radix: 2)) // initializer 'init(_:radix:uppercase:)' requires that 'Double' conform to 'BinaryInteger'
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 = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (n + m) / 2
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 avg = (Double(n) + Double(m)) / 2
return.success(String(avg.rounded(.toNearestOrAwayFromZero), 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) + Double(m)) / 2
return.success(String(avg.rounded(.toNearestOrAwayFromZero), radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return.success(String(avg.rounded(.toNearestOrAwayFromZero), radix: 2)) // initializer 'init(_:radix:uppercase:)' requires that 'Double' conform to 'BinaryInteger'
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) + Double(m)) / 2
return.success(String(avg.rounded(), 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) + Double(m)) / 2
return.success(String(avg.rounded(), radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return.success(String(avg.rounded(), radix: 2)) // initializer 'init(_:radix:uppercase:)' requires that 'Double' conform to 'BinaryInteger'
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) + Double(m)) / 2
return.success(String(avg.rounded(), 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) + Double(m)) / 2
return.success(String(avg.rounded(), radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return.success(String(avg.rounded(), radix: 2)) // initializer 'init(_:radix:uppercase:)' requires that 'Double' conform to 'BinaryInteger'
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) + Double(m)) / 2
return.success(String(avg.rounded(.toNearestOrAwayFromZero), 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) + Double(m)) / 2
return.success(String(avg.rounded(.toNearestOrAwayFromZero), radix: 2))
}
roundedAvg(n: 1, m: 5)
roundedAvg(n: 7, m: 5)
roundedAvg(n: 10, m: 20)
roundedAvg(n: 20, m: 33)
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return.success(String(avg.rounded(.toNearestOrAwayFromZero), radix: 2)) // initializer 'init(_:radix:uppercase:)' requires that 'Double' conform to 'BinaryInteger'
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) + Double(m)) / 2
return.success(String(avg.rounded(), 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) + Double(m)) / 2
return.success(String(avg.rounded(), radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return.success(String(avg.rounded(), radix: 2)) // initializer 'init(_:radix:uppercase:)' requires that 'Double' conform to 'BinaryInteger'
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0 % 2!= 0 }
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0 % 2!= 0 }
}
```
return x.filter { $0 % 2!= 0 } // cannot force unwrap value of non-optional type 'Int'
return x.filter { $0 % 2!= 0 } // expression is not assignable: binary operator returns immutable value
return x.filter { $0 % 2!= 0 } // '=' must have consistent whitespace on both sides
return x.filter { $0 % 2!= 0 } // cannot convert value of type '()' to closure result type 'Bool'
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter {
$0 % 2!= 0
}
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter {
$0 % 2!= 0
}
}
```
$0 % 2!= 0 // expression is not assignable: binary operator returns immutable value
$0 % 2!= 0 // '=' must have consistent whitespace on both sides
$0 % 2!= 0 // cannot convert value of type '()' to closure result type 'Bool'
$0 % 2!= 0 // cannot force unwrap value of non-optional type 'Int'
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
result.append(i)
}
}
return result
}
```
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
var temp = [Int]()
for i in x {
if i % 2!= 0 {
temp.append(i)
}
}
temp.sort()
for i in temp {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
var temp = [Int]()
for i in x {
if i % 2!= 0 {
temp.append(i)
}
}
temp.sort()
for i in temp {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
var temp = [Int]()
for i in x {
if i % 2!= 0 {
temp.append(i)
}
}
temp.sort()
for i in temp {
result.append(i)
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
var temp = [Int]()
for i in x {
if i % 2!= 0 {
temp.append(i)
}
}
temp.sort()
for i in temp {
result.append(i)
}
return result
}
```
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
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 % 2!= 0 {
result.append(i)
}
}
return result.sorted()
}
```
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
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 % 2!= 0 {
result.append(i)
}
}
return result.sorted()
}
```
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
result.append(i)
}
}
return result
}
```
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i % 2!= 0 {
result.append(i)
}
}
return result
}
```
if i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 2!= 0 { // '=' must have consistent whitespace on both sides
if i % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
while temp > 0 {
if temp % 10 == 0 {
temp /= 10
} else {
break
}
}
if temp == 0 {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
while temp > 0 {
if temp % 10 == 0 {
temp /= 10
} else {
break
}
}
if temp == 0 {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().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] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().map { String($0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().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] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().map { String($0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed().map { String(describing: $0) }
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed().map { String(describing: $0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 > 0 && $0 < 10 }.sorted().reversed().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 < 10 }.sorted().reversed().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 byLength(arr: [Int]) -> [String] {
return arr.filter({$0 >= 1 && $0 <= 9}).sorted().reversed().map({String(describing: $0)})
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.filter({$0 >= 1 && $0 <= 9}).sorted().reversed().map({String(describing: $0)})
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed().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] {
return arr.filter { $0 >= 1 && $0 <= 9 }.sorted().reversed().map { String($0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().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 >= 1 && $0 <= 9 }.reversed().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 ""
}
}
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().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] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().map { String($0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().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 >= 1 && $0 <= 9 }.reversed().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 ""
}
}
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().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] {
return arr.filter { $0 >= 1 && $0 <= 9 }.reversed().map { String($0) }
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
return (0..<n).map { i in
if i % 2 == 0 {
return i == 0? 1 : factorial(i)
} else {
return (1...i).reduce(0, +)
}
}
}
func factorial(_ n: Int) -> Int {
return (1...n).reduce(1, *)
}
```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] {
return (0..<n).map { i in
if i % 2 == 0 {
return i == 0? 1 : factorial(i)
} else {
return (1...i).reduce(0, +)
}
}
}
func factorial(_ n: Int) -> Int {
return (1...n).reduce(1, *)
}
```
return i == 0? 1 : factorial(i) // consecutive statements on a line must be separated by ';'
return i == 0? 1 : factorial(i) // cannot use optional chaining on non-optional value of type 'Int'
return i == 0? 1 : factorial(i) // cannot convert value of type 'Bool' to closure result type 'Int'
return i == 0? 1 : factorial(i) // expected expression
return i == 0? 1 : factorial(i) // consecutive statements on a line must be separated by ';'
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
return (1...n).map { i in
if i % 2 == 0 {
return i
} else {
return (1...i).reduce(0, +)
}
}
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
return (1...n).map { i in
if i % 2 == 0 {
return i
} else {
return (1...i).reduce(0, +)
}
}
}
f(n: 5)
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0? factorial(i) : sum(1...i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ range: ClosedRange<Int>) -> Int {
var result = 0
for i in range {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0? factorial(i) : sum(1...i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ range: ClosedRange<Int>) -> Int {
var result = 0
for i in range {
result += i
}
return result
}
f(n: 5)
```
result.append(i % 2 == 0? factorial(i) : sum(1...i)) // cannot use optional chaining on non-optional value of type 'Int'
result.append(i % 2 == 0? factorial(i) : sum(1...i)) // cannot convert value of type 'Bool' to expected argument type 'Int'
result.append(i % 2 == 0? factorial(i) : sum(1...i)) // expected ',' separator
result.append(i % 2 == 0? factorial(i) : sum(1...i)) // extra argument in call
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0? factorial(i) : sum(i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0? factorial(i) : sum(i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
result.append(i % 2 == 0? factorial(i) : sum(i)) // cannot use optional chaining on non-optional value of type 'Int'
result.append(i % 2 == 0? factorial(i) : sum(i)) // extra argument in call
result.append(i % 2 == 0? factorial(i) : sum(i)) // expected ',' separator
result.append(i % 2 == 0? factorial(i) : sum(i)) // cannot convert value of type 'Bool' to expected argument type 'Int'
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
return (0..<n).map { i in
if i % 2 == 0 {
return factorial(i)
} else {
return (1...i).reduce(0, +)
}
}
}
func factorial(_ n: Int) -> Int {
return (1...n).reduce(1, *)
}
```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] {
return (0..<n).map { i in
if i % 2 == 0 {
return factorial(i)
} else {
return (1...i).reduce(0, +)
}
}
}
func factorial(_ n: Int) -> Int {
return (1...n).reduce(1, *)
}
```
// Fatal error: Range requires lowerBound <= upperBound
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
return (1...n).map {
if $0 % 2 == 0 {
return $0
} else {
return (1...$0).reduce(0, +)
}
}
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num = num / 10
}
return reverse == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```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 isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num = num / 10
}
return reverse == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isEvenPalindrome(i) {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
func isEvenPalindrome(_ n: Int) -> Bool {
var n = n
var reversed = 0
while n > 0 {
reversed = 10 * reversed + n % 10
n /= 10
}
return reversed == n
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isEvenPalindrome(i) {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
func isEvenPalindrome(_ n: Int) -> Bool {
var n = n
var reversed = 0
while n > 0 {
reversed = 10 * reversed + n % 10
n /= 10
}
return reversed == n
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isEvenPalindrome(i) {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
func isEvenPalindrome(_ n: Int) -> Bool {
var n = n
var reversed = 0
while n > 0 {
reversed = reversed * 10 + n % 10
n /= 10
}
return reversed == n
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isEvenPalindrome(i) {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
func isEvenPalindrome(_ n: Int) -> Bool {
var n = n
var reversed = 0
while n > 0 {
reversed = reversed * 10 + n % 10
n /= 10
}
return reversed == n
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num = num / 10
}
return reverse == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```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 isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num = num / 10
}
return reverse == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var n = n
var reverse = 0
while n > 0 {
let digit = n % 10
reverse = reverse * 10 + digit
n /= 10
}
return reverse == n
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var n = n
var reverse = 0
while n > 0 {
let digit = n % 10
reverse = reverse * 10 + digit
n /= 10
}
return reverse == n
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return reversed == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```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 isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reversed = 0
while num > 0 {
reversed = reversed * 10 + num % 10
num /= 10
}
return reversed == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return reverse == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```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 isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return reverse == n
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let count = str.count
for i in 0..<count/2 {
if str[str.index(str.startIndex, offsetBy: i)]!= str[str.index(str.startIndex, offsetBy: count - i - 1)] {
return false
}
}
return true
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```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 isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let count = str.count
for i in 0..<count/2 {
if str[str.index(str.startIndex, offsetBy: i)]!= str[str.index(str.startIndex, offsetBy: count - i - 1)] {
return false
}
}
return true
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
```
if str[str.index(str.startIndex, offsetBy: i)]!= str[str.index(str.startIndex, offsetBy: count - i - 1)] { // '=' must have consistent whitespace on both sides
if str[str.index(str.startIndex, offsetBy: i)]!= str[str.index(str.startIndex, offsetBy: count - i - 1)] { // cannot force unwrap value of non-optional type 'Character'
if str[str.index(str.startIndex, offsetBy: i)]!= str[str.index(str.startIndex, offsetBy: count - i - 1)] { // use of '=' in a boolean context, did you mean '=='?
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
func isPalindrome(_ n: Int) -> Bool {
let s = String(n)
let count = s.count
for i in 0..<count/2 {
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: count - 1 - i)] {
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 isEven(i) {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
func isPalindrome(_ n: Int) -> Bool {
let s = String(n)
let count = s.count
for i in 0..<count/2 {
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: count - 1 - i)] {
return false
}
}
return true
}
```
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: count - 1 - i)] { // '=' must have consistent whitespace on both sides
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: count - 1 - i)] { // use of '=' in a boolean context, did you mean '=='?
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: count - 1 - i)] { // cannot force unwrap value of non-optional type 'Character'
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isEven(i) {
if isPalindrome(i) {
even += 1
}
} else {
if isPalindrome(i) {
odd += 1
}
}
}
return (even, odd)
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```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 isEven(i) {
if isPalindrome(i) {
even += 1
}
} else {
if isPalindrome(i) {
odd += 1
}
}
}
return (even, odd)
}
func isEven(_ n: Int) -> Bool {
return n % 2 == 0
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var num = num
while num!= 0 {
sum += num % 10
num /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var num = num
while num!= 0 {
sum += num % 10
num /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num < 0 {
var sum = 0
var num = num
while num!= 0 {
sum += abs(num % 10)
num /= 10
}
if sum > 0 {
count += 1
}
} else {
var sum = 0
var num = num
while num!= 0 {
sum += num % 10
num /= 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num < 0 {
var sum = 0
var num = num
while num!= 0 {
sum += abs(num % 10)
num /= 10
}
if sum > 0 {
count += 1
}
} else {
var sum = 0
var num = num
while num!= 0 {
sum += num % 10
num /= 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) {
$0 + ($1 > 0? 1 : 0)
}
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) {
$0 + ($1 > 0? 1 : 0)
}
}
```
$0 + ($1 > 0? 1 : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1 > 0? 1 : 0) // cannot use optional chaining on non-optional value of type 'Int'
$0 + ($1 > 0? 1 : 0) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0 + ($1 > 0? 1 : 0) // expected ',' separator
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { $0 + $1.countDigits() }
}
extension Int {
func countDigits() -> Int {
return abs(self) > 0? String(self).count : 1
}
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { $0 + $1.countDigits() }
}
extension Int {
func countDigits() -> Int {
return abs(self) > 0? String(self).count : 1
}
}
```
return abs(self) > 0? String(self).count : 1 // cannot convert return expression of type 'Bool' to return type 'Int'
return abs(self) > 0? String(self).count : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return abs(self) > 0? String(self).count : 1 // expected expression
return abs(self) > 0? String(self).count : 1 // cannot use optional chaining on non-optional value of type 'Int'
return abs(self) > 0? String(self).count : 1 // expression of type 'Int' is unused
return abs(self) > 0? String(self).count : 1 // consecutive statements on a line must be separated by ';'
return abs(self) > 0? String(self).count : 1 // consecutive statements on a line must be separated by ';'
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) { $0 + $1.digits.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 {
return arr.reduce(0) { $0 + $1.digits.count }
}
```
return arr.reduce(0) { $0 + $1.digits.count } // value of type 'Int' has no member 'digits'
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num < 0 {
let absNum = abs(num)
if absNum > 0 {
count += 1
}
} else {
if num > 0 {
count += 1
}
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num < 0 {
let absNum = abs(num)
if absNum > 0 {
count += 1
}
} else {
if num > 0 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
return 0
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return 0
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
return arr.filter { $0 > 0 }.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 {
return arr.filter { $0 > 0 }.count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
return 0
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return 0
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) {
$0 + ($1 > 0? 1 : 0)
}
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.reduce(0) {
$0 + ($1 > 0? 1 : 0)
}
}
```
$0 + ($1 > 0? 1 : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1 > 0? 1 : 0) // cannot use optional chaining on non-optional value of type 'Int'
$0 + ($1 > 0? 1 : 0) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0 + ($1 > 0? 1 : 0) // expected ',' separator
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i]!= i + 1 {
count += 1
if count > 1 {
return false
}
var j = i
while j > 0 && arr[j]!= j + 1 {
swap(&arr, j, j - 1)
j -= 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 {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i]!= i + 1 {
count += 1
if count > 1 {
return false
}
var j = i
while j > 0 && arr[j]!= j + 1 {
swap(&arr, j, j - 1)
j -= 1
}
}
}
return true
}
```
if arr[i]!= i + 1 { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= i + 1 { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= i + 1 { // '=' must have consistent whitespace on both sides
while j > 0 && arr[j]!= j + 1 { // use of '=' in a boolean context, did you mean '=='?
while j > 0 && arr[j]!= j + 1 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
while j > 0 && arr[j]!= j + 1 { // '=' must have consistent whitespace on both sides
while j > 0 && arr[j]!= j + 1 { // cannot force unwrap value of non-optional type 'Int'
while j > 0 && arr[j]!= j + 1 { // expression is not assignable: '&&' returns immutable value
swap(&arr, j, j - 1) // cannot convert value of type 'Int' to expected argument type '[Int]'
swap(&arr, j, j - 1) // extra argument in call
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
var j = 0
while i < arr.count {
if arr[i] < arr[i + 1] {
i += 1
} else {
j = i + 1
while j < arr.count && arr[j] < arr[i] {
j += 1
}
if j < arr.count {
count += 1
for k in j...i {
arr.swapAt(k, i)
}
} else {
return false
}
}
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
var j = 0
while i < arr.count {
if arr[i] < arr[i + 1] {
i += 1
} else {
j = i + 1
while j < arr.count && arr[j] < arr[i] {
j += 1
}
if j < arr.count {
count += 1
for k in j...i {
arr.swapAt(k, i)
}
} else {
return false
}
}
}
return count <= 1
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
arr[i] -= 1
arr[i+1] += 1
}
}
return count % 2 == 0
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
arr[i] -= 1
arr[i+1] += 1
}
}
return count % 2 == 0
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
var j = 1
while i < arr.count && j < arr.count {
if arr[i] > arr[j] {
count += 1
i += 1
j += 1
} else {
i += 1
}
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
var j = 1
while i < arr.count && j < arr.count {
if arr[i] > arr[j] {
count += 1
i += 1
j += 1
} else {
i += 1
}
}
return count <= 1
}
moveOneBall(arr: [3, 4, 5, 1, 2])
moveOneBall(arr: [3, 5, 4, 1, 2])
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i + 1] {
count += 1
}
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i + 1] {
count += 1
}
}
return count <= 1
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
}
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
}
}
return count <= 1
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// Fatal error: Range requires lowerBound <= upperBound
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
count += 1
i += 1
}
i += 1
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
count += 1
i += 1
}
i += 1
}
return count <= 1
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var i = 0
var j = 0
var count = 0
while i < arr.count {
if arr[i] == i + 1 {
i += 1
continue
}
j = i + 1
while j < arr.count {
if arr[j] == i + 1 {
arr.swapAt(i, j)
count += 1
break
}
j += 1
}
i += 1
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var i = 0
var j = 0
var count = 0
while i < arr.count {
if arr[i] == i + 1 {
i += 1
continue
}
j = i + 1
while j < arr.count {
if arr[j] == i + 1 {
arr.swapAt(i, j)
count += 1
break
}
j += 1
}
i += 1
}
return count <= 1
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
count += 1
i += 1
}
i += 1
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
count += 1
i += 1
}
i += 1
}
return count <= 1
}
moveOneBall(arr: [3, 4, 5, 1, 2])
moveOneBall(arr: [3, 5, 4, 1, 2])
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
arr[i] = arr[i+1]
arr[i+1] = arr[i]
}
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
count += 1
arr[i] = arr[i+1]
arr[i+1] = arr[i]
}
}
return count <= 1
}
```
// Fatal error: Range requires lowerBound <= upperBound
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1Even = [Int]()
var lst2Even = [Int]()
var lst1Odd = [Int]()
var lst2Odd = [Int]()
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1Even.append(lst1[i])
} else {
lst1Odd.append(lst1[i])
}
if lst2[i] % 2 == 0 {
lst2Even.append(lst2[i])
} else {
lst2Odd.append(lst2[i])
}
}
if lst1Even.count!= lst2Even.count {
result = "NO"
} else {
for i in 0..<lst1Even.count {
if lst1Even[i]!= lst2Even[i] {
result = "NO"
break
}
}
}
if result == "YES" {
for i in 0..<lst1Odd.count {
if lst1Odd[i]!= lst2Odd[i] {
result = "NO"
break
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1Even = [Int]()
var lst2Even = [Int]()
var lst1Odd = [Int]()
var lst2Odd = [Int]()
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1Even.append(lst1[i])
} else {
lst1Odd.append(lst1[i])
}
if lst2[i] % 2 == 0 {
lst2Even.append(lst2[i])
} else {
lst2Odd.append(lst2[i])
}
}
if lst1Even.count!= lst2Even.count {
result = "NO"
} else {
for i in 0..<lst1Even.count {
if lst1Even[i]!= lst2Even[i] {
result = "NO"
break
}
}
}
if result == "YES" {
for i in 0..<lst1Odd.count {
if lst1Odd[i]!= lst2Odd[i] {
result = "NO"
break
}
}
}
return result
}
```
if lst1Even.count!= lst2Even.count { // '=' must have consistent whitespace on both sides
if lst1Even.count!= lst2Even.count { // cannot force unwrap value of non-optional type 'Int'
if lst1Even.count!= lst2Even.count { // use of '=' in a boolean context, did you mean '=='?
if lst1Even[i]!= lst2Even[i] { // cannot force unwrap value of non-optional type 'Int'
if lst1Even[i]!= lst2Even[i] { // use of '=' in a boolean context, did you mean '=='?
if lst1Even[i]!= lst2Even[i] { // '=' must have consistent whitespace on both sides
if lst1Odd[i]!= lst2Odd[i] { // '=' must have consistent whitespace on both sides
if lst1Odd[i]!= lst2Odd[i] { // use of '=' in a boolean context, did you mean '=='?
if lst1Odd[i]!= lst2Odd[i] { // cannot force unwrap value of non-optional type 'Int'
func exchange(lst1: [Int], lst2: [Int]) -> String {
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 {
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2!= 0 {
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2!= 0 {
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
}
return result
}
exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4])
exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4])
```
if lst1[i] % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if lst1[i] % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if lst1[i] % 2!= 0 { // '=' must have consistent whitespace on both sides
if lst1[i] % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2!= 0 {
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2!= 0 {
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
}
return result
}
```
if lst1[i] % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if lst1[i] % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if lst1[i] % 2!= 0 { // '=' must have consistent whitespace on both sides
if lst1[i] % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
var result = "NO"
for i in 0..<lst1.count {
if lst1[i] % 2!= 0 {
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
count += 1
break
}
}
}
}
if count == lst1.count {
result = "YES"
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
var result = "NO"
for i in 0..<lst1.count {
if lst1[i] % 2!= 0 {
for j in 0..<lst2.count {
if lst2[j] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
count += 1
break
}
}
}
}
if count == lst1.count {
result = "YES"
}
return result
}
```
if lst1[i] % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if lst1[i] % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if lst1[i] % 2!= 0 { // '=' must have consistent whitespace on both sides
if lst1[i] % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "NO"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
if result == "YES" {
break
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "NO"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
if result == "YES" {
break
}
}
return result
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "NO"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "NO"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4])
exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4])
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var result = "YES"
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[j]
lst2[j] = lst1[i]
result = "YES"
break
}
}
}
return result
}
```
// XCTAssertTrue failed
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 array = test.components(separatedBy: " ")
for item in array {
if dict[item] == nil {
dict[item] = 1
} else {
dict[item]! += 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 array = test.components(separatedBy: " ")
for item in array {
if dict[item] == nil {
dict[item] = 1
} else {
dict[item]! += 1
}
}
return dict
}
```
// XCTAssertTrue failed
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 array = test.components(separatedBy: " ")
for item in array {
if let value = dict[item] {
dict[item] = value + 1
} else {
dict[item] = 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 array = test.components(separatedBy: " ")
for item in array {
if let value = dict[item] {
dict[item] = value + 1
} else {
dict[item] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
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 array = test.components(separatedBy: " ")
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String: Int]()
let array = test.components(separatedBy: " ")
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i]! += 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String:Int]()
let arr = test.components(separatedBy: " ")
for i in arr {
if let value = dict[i] {
dict[i] = value + 1
} else {
dict[i] = 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String:Int]()
let arr = test.components(separatedBy: " ")
for i in arr {
if let value = dict[i] {
dict[i] = value + 1
} else {
dict[i] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String: Int]()
let array = test.components(separatedBy: " ")
for i in array {
if let value = dict[i] {
dict[i] = value + 1
} else {
dict[i] = 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String: Int]()
let array = test.components(separatedBy: " ")
for i in array {
if let value = dict[i] {
dict[i] = value + 1
} else {
dict[i] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String: Int]()
var max = 0
var maxKey = ""
for char in test {
let key = String(char)
if result[key] == nil {
result[key] = 1
} else {
result[key] = result[key]! + 1
}
if result[key]! > max {
max = result[key]!
maxKey = key
}
}
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 result = [String: Int]()
var max = 0
var maxKey = ""
for char in test {
let key = String(char)
if result[key] == nil {
result[key] = 1
} else {
result[key] = result[key]! + 1
}
if result[key]! > max {
max = result[key]!
maxKey = key
}
}
result[maxKey] = max
return result
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String: Int]()
var max = 0
var maxKey = ""
for char in test {
if dict[String(char)] == nil {
dict[String(char)] = 1
} else {
dict[String(char)]! += 1
}
if dict[String(char)]! > max {
max = dict[String(char)]!
maxKey = String(char)
}
}
dict[maxKey] = max
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String: Int]()
var max = 0
var maxKey = ""
for char in test {
if dict[String(char)] == nil {
dict[String(char)] = 1
} else {
dict[String(char)]! += 1
}
if dict[String(char)]! > max {
max = dict[String(char)]!
maxKey = String(char)
}
}
dict[maxKey] = max
return dict
}
```
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
// Test
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
} else {
check.append(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 = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
} else {
check.append(char)
}
}
return (result, result == String(result.reversed()))
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for char in result {
check.append(char)
}
return (check, check == String(check.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for char in result {
check.append(char)
}
return (check, check == String(check.reversed()))
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
}
}
check = String(result.reversed())
return (check, check == result)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
}
}
check = String(result.reversed())
return (check, check == result)
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result += String(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result += String(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for char in result {
check.append(char)
}
return (check, check == String(check.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var check = ""
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for char in result {
check.append(char)
}
return (check, check == String(check.reversed()))
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for i in 0..<result.count/2 {
if result[i]!= result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for i in 0..<result.count/2 {
if result[i]!= result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
if result[i]!= result[result.count - 1 - i] { // '=' must have consistent whitespace on both sides
if result[i]!= result[result.count - 1 - i] { // use of '=' in a boolean context, did you mean '=='?
if result[i]!= result[result.count - 1 - i] { // cannot force unwrap value of non-optional type 'Character'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for i in 0..<result.count/2 {
if result[i]!= result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for i in 0..<result.count/2 {
if result[i]!= result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
reverseDelete(s: "abcde", c: "ae")
reverseDelete(s: "abcdef", c: "b")
reverseDelete(s: "abcdedcba", c: "ab")
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
if result[i]!= result[result.count - 1 - i] { // '=' must have consistent whitespace on both sides
if result[i]!= result[result.count - 1 - i] { // use of '=' in a boolean context, did you mean '=='?
if result[i]!= result[result.count - 1 - i] { // cannot force unwrap value of non-optional type 'Character'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for i in 0..<result.count/2 {
if result[i]!= result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if!c.contains(char) {
result.append(char)
}
}
for i in 0..<result.count/2 {
if result[i]!= result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```
if!c.contains(char) { // expected expression, var, or let in 'if' condition
if result[i]!= result[result.count - 1 - i] { // '=' must have consistent whitespace on both sides
if result[i]!= result[result.count - 1 - i] { // use of '=' in a boolean context, did you mean '=='?
if result[i]!= result[result.count - 1 - i] { // cannot force unwrap value of non-optional type 'Character'
func oddCount(lst: [String]) -> [String] {
return lst.map {
var count = 0
for char in $0 {
if char.isDigit {
count += 1
}
}
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
var count = 0
for char in $0 {
if char.isDigit {
count += 1
}
}
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.filter { $0.isDigit }.count
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.filter { $0.isDigit }.count
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```
let odd = $0.filter { $0.isDigit }.count // value of type 'String.Element' (aka 'Character') has no member 'isDigit'
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.filter { $0.isDigit }.count
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.filter { $0.isDigit }.count
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```
let odd = $0.filter { $0.isDigit }.count // value of type 'String.Element' (aka 'Character') has no member 'isDigit'
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.filter { $0.isDigit }.count
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.filter { $0.isDigit }.count
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```
let odd = $0.filter { $0.isDigit }.count // value of type 'String.Element' (aka 'Character') has no member 'isDigit'
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = $0.reduce(0) { $0 + Int(String($1))! % 2 }
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = $0.reduce(0) { $0 + Int(String($1))! % 2 }
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.reduce(0) { $0 + ($1.isDigit? 1 : 0) }
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.reduce(0) { $0 + ($1.isDigit? 1 : 0) }
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```
return lst.map { // type of expression is ambiguous without a type annotation
let odd = $0.reduce(0) { $0 + ($1.isDigit? 1 : 0) } // expected ',' separator
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let odd = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
return "the number of odd elements \(odd)n the str\(odd)ng \(odd) of the \(odd)nput."
}
}
```
let odd = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // missing argument label 'into:' in call
let odd = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // cannot use optional chaining on non-optional value of type 'String'
let odd = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // type '(Bool, Int)' cannot conform to 'AttributedStringProtocol'
let odd = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // expected ',' separator
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```
let count = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // missing argument label 'into:' in call
let count = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // cannot use optional chaining on non-optional value of type 'String'
let count = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // type '(Bool, Int)' cannot conform to 'AttributedStringProtocol'
let count = $0.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // expected ',' separator
func oddCount(lst: [String]) -> [String] {
return lst.map {
let oddCount = $0.reduce(0) {
$0 + ($1 == "1"? 1 : 0)
}
return "the number of odd elements \(oddCount)n the str\(oddCount)ng \(oddCount) of the \(oddCount)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let oddCount = $0.reduce(0) {
$0 + ($1 == "1"? 1 : 0)
}
return "the number of odd elements \(oddCount)n the str\(oddCount)ng \(oddCount) of the \(oddCount)nput."
}
}
```
let oddCount = $0.reduce(0) { // missing argument label 'into:' in call
$0 + ($1 == "1"? 1 : 0) // type '(Bool, Int)' cannot conform to 'AttributedStringProtocol'
$0 + ($1 == "1"? 1 : 0) // expected ',' separator
$0 + ($1 == "1"? 1 : 0) // cannot use optional chaining on non-optional value of type 'String'
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = $0.reduce(0) {
$0 + ($1 == "1"? 1 : 0)
}
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = $0.reduce(0) {
$0 + ($1 == "1"? 1 : 0)
}
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
```
let count = $0.reduce(0) { // missing argument label 'into:' in call
$0 + ($1 == "1"? 1 : 0) // type '(Bool, Int)' cannot conform to 'AttributedStringProtocol'
$0 + ($1 == "1"? 1 : 0) // expected ',' separator
$0 + ($1 == "1"? 1 : 0) // cannot use optional chaining on non-optional value of type 'String'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var min = Int.max
var sum = 0
for num in nums {
sum += num
min = min(min, sum)
if sum < 0 {
sum = 0
}
}
return min
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var min = Int.max
var sum = 0
for num in nums {
sum += num
min = min(min, sum)
if sum < 0 {
sum = 0
}
}
return min
}
```
min = min(min, sum) // cannot call value of non-function type 'Int'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
for j in i+1..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
sum -= nums[j]
}
sum = 0
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
for j in i+1..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
sum -= nums[j]
}
sum = 0
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
sum -= nums[j]
}
sum = 0
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
sum -= nums[j]
}
sum = 0
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = 0
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var min = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
min = min < sum? min : sum
for j in i+1..<nums.count {
sum -= nums[i]
min = min < sum? min : sum
}
}
return min
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var min = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
min = min < sum? min : sum
for j in i+1..<nums.count {
sum -= nums[i]
min = min < sum? min : sum
}
}
return min
}
```
min = min < sum? min : sum // cannot use optional chaining on non-optional value of type 'Int'
min = min < sum? min : sum // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
min = min < sum? min : sum // expected expression
min = min < sum? min : sum // consecutive statements on a line must be separated by ';'
min = min < sum? min : sum // consecutive statements on a line must be separated by ';'
min = min < sum? min : sum // variable is unused
min = min < sum? min : sum // cannot assign value of type 'Bool' to type 'Int'
min = min < sum? min : sum // consecutive statements on a line must be separated by ';'
min = min < sum? min : sum // expected expression
min = min < sum? min : sum // variable is unused
min = min < sum? min : sum // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
min = min < sum? min : sum // consecutive statements on a line must be separated by ';'
min = min < sum? min : sum // cannot assign value of type 'Bool' to type 'Int'
min = min < sum? min : sum // cannot use optional chaining on non-optional value of type 'Int'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var queue = [Int]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append(i)
queue.append(j)
}
}
}
while!queue.isEmpty {
let i = queue.removeFirst()
let j = queue.removeFirst()
if i > 0 && grid[i - 1][j] == 0 {
grid[i - 1][j] = 1
queue.append(i - 1)
queue.append(j)
result += 1
}
if i < grid.count - 1 && grid[i + 1][j] == 0 {
grid[i + 1][j] = 1
queue.append(i + 1)
queue.append(j)
result += 1
}
if j > 0 && grid[i][j - 1] == 0 {
grid[i][j - 1] = 1
queue.append(i)
queue.append(j - 1)
result += 1
}
if j < grid[i].count - 1 && grid[i][j + 1] == 0 {
grid[i][j + 1] = 1
queue.append(i)
queue.append(j + 1)
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 {
var result = 0
var queue = [Int]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append(i)
queue.append(j)
}
}
}
while!queue.isEmpty {
let i = queue.removeFirst()
let j = queue.removeFirst()
if i > 0 && grid[i - 1][j] == 0 {
grid[i - 1][j] = 1
queue.append(i - 1)
queue.append(j)
result += 1
}
if i < grid.count - 1 && grid[i + 1][j] == 0 {
grid[i + 1][j] = 1
queue.append(i + 1)
queue.append(j)
result += 1
}
if j > 0 && grid[i][j - 1] == 0 {
grid[i][j - 1] = 1
queue.append(i)
queue.append(j - 1)
result += 1
}
if j < grid[i].count - 1 && grid[i][j + 1] == 0 {
grid[i][j + 1] = 1
queue.append(i)
queue.append(j + 1)
result += 1
}
}
return result
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var maxFill = 0
var grid = grid
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
var left = j
var right = j
var top = i
var bottom = i
while left >= 0 && grid[top][left] == 1 {
grid[top][left] = 2
left -= 1
}
while right < grid[i].count && grid[top][right] == 1 {
grid[top][right] = 2
right += 1
}
while top >= 0 && grid[top][left] == 1 {
grid[top][left] = 2
top -= 1
}
while bottom < grid.count && grid[bottom][left] == 1 {
grid[bottom][left] = 2
bottom += 1
}
maxFill += right - left - 1
}
}
}
return maxFill
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var maxFill = 0
var grid = grid
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
var left = j
var right = j
var top = i
var bottom = i
while left >= 0 && grid[top][left] == 1 {
grid[top][left] = 2
left -= 1
}
while right < grid[i].count && grid[top][right] == 1 {
grid[top][right] = 2
right += 1
}
while top >= 0 && grid[top][left] == 1 {
grid[top][left] = 2
top -= 1
}
while bottom < grid.count && grid[bottom][left] == 1 {
grid[bottom][left] = 2
bottom += 1
}
maxFill += right - left - 1
}
}
}
return maxFill
}
```
// Fatal error: Index out of range
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var water = 0
var i = 0
var j = 0
var max = 0
while i < grid.count {
j = 0
while j < grid[i].count {
if grid[i][j] == 1 {
water += 1
}
j += 1
}
if water > max {
max = water
}
i += 1
}
result = max / capacity
if max % capacity > 0 {
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 {
var result = 0
var water = 0
var i = 0
var j = 0
var max = 0
while i < grid.count {
j = 0
while j < grid[i].count {
if grid[i][j] == 1 {
water += 1
}
j += 1
}
if water > max {
max = water
}
i += 1
}
result = max / capacity
if max % capacity > 0 {
result += 1
}
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var grid = grid
var count = 0
var i = 0
var j = 0
while i < grid.count && j < grid[i].count {
if grid[i][j] == 1 {
let capacity = capacity
var k = i
while k < grid.count && grid[k][j] == 1 {
grid[k][j] = 0
k += 1
}
count += 1
j += 1
} else {
j += 1
}
}
return count
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var grid = grid
var count = 0
var i = 0
var j = 0
while i < grid.count && j < grid[i].count {
if grid[i][j] == 1 {
let capacity = capacity
var k = i
while k < grid.count && grid[k][j] == 1 {
grid[k][j] = 0
k += 1
}
count += 1
j += 1
} else {
j += 1
}
}
return count
}
```
var i = 0 // variable 'i' was never mutated; consider changing to 'let' constant
let capacity = capacity // initialization of immutable value 'capacity' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var i = 0
var j = 0
while i < grid.count && j < grid[i].count {
if grid[i][j] == 1 {
result += 1
j += 1
} else {
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 i = 0
var j = 0
while i < grid.count && j < grid[i].count {
if grid[i][j] == 1 {
result += 1
j += 1
} else {
i += 1
}
}
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var water = 0
var i = 0
var j = 0
var max = 0
while i < grid.count {
while j < grid[i].count {
if grid[i][j] == 1 {
water += capacity
count += 1
}
j += 1
}
i += 1
}
i = 0
j = 0
while i < grid.count {
while j < grid[i].count {
if grid[i][j] == 1 {
if water >= capacity {
water -= capacity
count -= 1
} else {
max = max > count? max : count
count = 0
water = 0
}
}
j += 1
}
i += 1
}
return max > count? max : count
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var water = 0
var i = 0
var j = 0
var max = 0
while i < grid.count {
while j < grid[i].count {
if grid[i][j] == 1 {
water += capacity
count += 1
}
j += 1
}
i += 1
}
i = 0
j = 0
while i < grid.count {
while j < grid[i].count {
if grid[i][j] == 1 {
if water >= capacity {
water -= capacity
count -= 1
} else {
max = max > count? max : count
count = 0
water = 0
}
}
j += 1
}
i += 1
}
return max > count? max : count
}
```
max = max > count? max : count // cannot use optional chaining on non-optional value of type 'Int'
max = max > count? max : count // consecutive statements on a line must be separated by ';'
max = max > count? max : count // variable is unused
max = max > count? max : count // expected expression
max = max > count? max : count // cannot assign value of type 'Bool' to type 'Int'
max = max > count? max : count // consecutive statements on a line must be separated by ';'
max = max > count? max : count // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return max > count? max : count // consecutive statements on a line must be separated by ';'
return max > count? max : count // variable is unused
return max > count? max : count // cannot convert return expression of type 'Bool' to return type 'Int'
return max > count? max : count // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return max > count? max : count // expected expression
return max > count? max : count // cannot use optional chaining on non-optional value of type 'Int'
return max > count? max : count // consecutive statements on a line must be separated by ';'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var water = 0
var i = 0
var j = 0
while i < grid.count && j < grid[0].count {
if grid[i][j] == 1 {
water += 1
if water == capacity {
result += 1
water = 0
}
} else {
water = 0
}
j += 1
if j == grid[0].count {
j = 0
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 water = 0
var i = 0
var j = 0
while i < grid.count && j < grid[0].count {
if grid[i][j] == 1 {
water += 1
if water == capacity {
result += 1
water = 0
}
} else {
water = 0
}
j += 1
if j == grid[0].count {
j = 0
i += 1
}
}
return result
}
```
// XCTAssertTrue failed
```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 current = 0
var next = 0
var prev = 0
var prevNext = 0
var prevPrev = 0
var prevPrevNext = 0
var prevPrevPrev = 0
var prevPrevPrevNext = 0
var prevPrevPrevPrev = 0
var prevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrev = 0
var prevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrev = 0
var prevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrev = 0
var prevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrev = 0
var prevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrev = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevNext = 0
var prevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrevPrev
XCTAssertTrue(maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[1, 1, 1, 1], [1, 1, 1, 1]], capacity: 2) == 4) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[1, 1, 1, 1], [1, 1, 1, 1]], capacity: 9) == 2) // cannot find 'maxFill' in scope
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var maxFill = 0
var currentFill = 0
var currentWell = 0
var currentBucket = 0
var currentWells = 0
var currentBuckets = 0
var currentWellsFilled = 0
var currentBucketsFilled = 0
var currentWellsFilledBuckets = 0
var currentBucketsFilledWells = 0
var currentWellsFilledBucketsWells = 0
var currentBucketsFilledWellsWells = 0
var currentWellsFilledBucketsWellsWells = 0
var currentWellsFilledBucketsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentBucketsFilledWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsBuckets = 0
var currentWellsFilledBucketsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWellsWell
XCTAssertTrue(maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[1, 1, 1, 1], [1, 1, 1, 1]], capacity: 2) == 4) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[1, 1, 1, 1], [1, 1, 1, 1]], capacity: 9) == 2) // cannot find 'maxFill' in scope
```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 currentRow = 0
var currentColumn = 0
var currentCapacity = 0
var currentWell = 0
var currentBucket = 0
var currentWells = 0
var currentBuckets = 0
var currentWellsAndBuckets = 0
var currentWellsAndBucketsAndCapacity = 0
var currentWellsAndBucketsAndCapacityAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWell = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucket = 0
var currentWellsAndBucketsAndCapacityAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAndWellAndBucketAnd
XCTAssertTrue(maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[1, 1, 1, 1], [1, 1, 1, 1]], capacity: 2) == 4) // cannot find 'maxFill' in scope
XCTAssertTrue(maxFill(grid: [[1, 1, 1, 1], [1, 1, 1, 1]], capacity: 9) == 2) // cannot find 'maxFill' in scope
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = $0.binaryString.filter { $0 == "1" }.count
let b = $1.binaryString.filter { $0 == "1" }.count
return a == b? $0 < $1 : a < b
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = $0.binaryString.filter { $0 == "1" }.count
let b = $1.binaryString.filter { $0 == "1" }.count
return a == b? $0 < $1 : a < b
}
}
```
let a = $0.binaryString.filter { $0 == "1" }.count // value of type 'Int' has no member 'binaryString'
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // expected expression
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // extra argument 'radix' in call
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // expected expression
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0), radix: 2)
let binary2 = String(String(format: "%d", $1), radix: 2)
let ones1 = binary1.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
let ones2 = binary2.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
return ones1 == ones2? $0 < $1 : ones1 < ones2
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0), radix: 2)
let binary2 = String(String(format: "%d", $1), radix: 2)
let ones1 = binary1.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
let ones2 = binary2.reduce(0) { $0 + ($1 == "1"? 1 : 0) }
return ones1 == ones2? $0 < $1 : ones1 < ones2
}
}
```
let binary1 = String(String(format: "%d", $0), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
let ones1 = binary1.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // expected ',' separator
let ones2 = binary2.reduce(0) { $0 + ($1 == "1"? 1 : 0) } // expected ',' separator
return ones1 == ones2? $0 < $1 : ones1 < ones2 // consecutive statements on a line must be separated by ';'
return ones1 == ones2? $0 < $1 : ones1 < ones2 // consecutive statements on a line must be separated by ';'
return ones1 == ones2? $0 < $1 : ones1 < ones2 // expected expression
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0), radix: 2)
let binary2 = String(String(format: "%d", $1), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0), radix: 2)
let binary2 = String(String(format: "%d", $1), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count
}
}
```
let binary1 = String(String(format: "%d", $0), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count // expected expression
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // extra argument 'radix' in call
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // expected expression
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String(format: "%d", $0)
let b = String(format: "%d", $1)
return a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count? a.count > b.count : a.filter { $0 == "1" }.count > b.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String(format: "%d", $0)
let b = String(format: "%d", $1)
return a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count? a.count > b.count : a.filter { $0 == "1" }.count > b.filter { $0 == "1" }.count
}
}
```
return a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count? a.count > b.count : a.filter { $0 == "1" }.count > b.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count? a.count > b.count : a.filter { $0 == "1" }.count > b.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count? a.count > b.count : a.filter { $0 == "1" }.count > b.filter { $0 == "1" }.count // expected expression
return a.filter { $0 == "1" }.count == b.filter { $0 == "1" }.count? a.count > b.count : a.filter { $0 == "1" }.count > b.filter { $0 == "1" }.count // cannot use optional chaining on non-optional value of type 'Int'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // extra argument 'radix' in call
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // expected expression
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 > $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2)
let binary2 = String(String(format: "%d", $1, radix: 2), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 > $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count
}
}
```
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
let binary1 = String(String(format: "%d", $0, radix: 2), radix: 2) // extra argument 'radix' in call
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 > $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 > $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // expected expression
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 > $1 : binary1.filter { $0 == "1" }.count > binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0), radix: 2)
let binary2 = String(String(format: "%d", $1), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let binary1 = String(String(format: "%d", $0), radix: 2)
let binary2 = String(String(format: "%d", $1), radix: 2)
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count
}
}
```
let binary1 = String(String(format: "%d", $0), radix: 2) // initializer 'init(_:radix:uppercase:)' requires that 'String' conform to 'BinaryInteger'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count // expected expression
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
return binary1.filter { $0 == "1" }.count == binary2.filter { $0 == "1" }.count? $0 < $1 : binary1.filter { $0 == "1" }.count < binary2.filter { $0 == "1" }.count // consecutive statements on a line must be separated by ';'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String(abs($0), radix: 2).filter { $0 == "1" }.count
let b = String(abs($1), radix: 2).filter { $0 == "1" }.count
return a == b? $0 < $1 : a < b
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String(abs($0), radix: 2).filter { $0 == "1" }.count
let b = String(abs($1), radix: 2).filter { $0 == "1" }.count
return a == b? $0 < $1 : a < b
}
}
```
return a == b? $0 < $1 : a < b // expected expression
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // consecutive statements on a line must be separated by ';'
return a == b? $0 < $1 : a < b // cannot use optional chaining on non-optional value of type 'Int'
func selectWords(s: String, n: Int) -> [String] {
return []
}
```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] {
return []
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = [String]()
var word = ""
for char in s {
if char.isLetter {
word.append(char)
} else {
if word.count == n {
words.append(word)
}
word = ""
}
}
if word.count == n {
words.append(word)
}
return words
}
```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 = [String]()
var word = ""
for char in s {
if char.isLetter {
word.append(char)
} else {
if word.count == n {
words.append(word)
}
word = ""
}
}
if word.count == n {
words.append(word)
}
return words
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var result = [String]()
var word = ""
var count = 0
for char in s {
if char == " " {
if count == n {
result.append(word)
}
word = ""
count = 0
} else if char.isLetter {
word.append(char)
count += 1
}
}
if count == n {
result.append(word)
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var result = [String]()
var word = ""
var count = 0
for char in s {
if char == " " {
if count == n {
result.append(word)
}
word = ""
count = 0
} else if char.isLetter {
word.append(char)
count += 1
}
}
if count == n {
result.append(word)
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
return s.components(separatedBy: " ").filter { word in
word.components(separatedBy: "aeiou").count == n
}
}
```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] {
return s.components(separatedBy: " ").filter { word in
word.components(separatedBy: "aeiou").count == n
}
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
return s.components(separatedBy: " ").filter {
$0.components(separatedBy: "aeiou").count == n
}
}
```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] {
return s.components(separatedBy: " ").filter {
$0.components(separatedBy: "aeiou").count == n
}
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var result = [String]()
let words = s.components(separatedBy: " ")
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 result = [String]()
let words = s.components(separatedBy: " ")
for word in words {
if word.count == n {
result.append(word)
}
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let 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] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
if word.count == n {
result.append(word)
}
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var result: [String] = []
var word: String = ""
var count = 0
for char in s {
if char.isLetter {
word += String(char)
} else {
if word.count == n {
result.append(word)
}
word = ""
count = 0
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var result: [String] = []
var word: String = ""
var count = 0
for char in s {
if char.isLetter {
word += String(char)
} else {
if word.count == n {
result.append(word)
}
word = ""
count = 0
}
}
return result
}
```
var count = 0 // variable 'count' was written to, but never read
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = [String]()
var word = [Character]()
var count = 0
for char in s {
if char == " " {
if count == n {
words.append(String(word))
}
word.removeAll()
count = 0
} else if char.isLetter {
word.append(char)
count += 1
}
}
if count == n {
words.append(String(word))
}
return words
}
```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 = [String]()
var word = [Character]()
var count = 0
for char in s {
if char == " " {
if count == n {
words.append(String(word))
}
word.removeAll()
count = 0
} else if char.isLetter {
word.append(char)
count += 1
}
}
if count == n {
words.append(String(word))
}
return words
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
return s.components(separatedBy: " ").filter {
$0.components(separatedBy: "aeiou").count == n
}
}
```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] {
return s.components(separatedBy: " ").filter {
$0.components(separatedBy: "aeiou").count == n
}
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = j - i
if distance < minDistance {
minDistance = distance
result = String(word[j])
}
}
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = j - i
if distance < minDistance {
minDistance = distance
result = String(word[j])
}
}
}
}
}
return result
}
```
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if vowels.contains(word[j]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = String(word[j]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = abs(i - j)
if distance < minDistance {
minDistance = distance
result = word[j]
}
}
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = abs(i - j)
if distance < minDistance {
minDistance = distance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = abs(i - j)
if distance < minDistance {
minDistance = distance
result = word[j]
}
}
}
}
}
return result
}
```
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if vowels.contains(word[j]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = word[j] // cannot assign value of type 'Character' to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
var closestVowel = ""
var closestVowelDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if consonants.contains(word[j]) {
let distance = abs(i - j)
if distance < closestVowelDistance {
closestVowelDistance = distance
closestVowel = String(word[j])
}
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"
var closestVowel = ""
var closestVowelDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if consonants.contains(word[j]) {
let distance = abs(i - j)
if distance < closestVowelDistance {
closestVowelDistance = distance
closestVowel = String(word[j])
}
break
}
}
}
}
return closestVowel
}
```
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if consonants.contains(word[j]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
closestVowel = String(word[j]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = abs(i - j)
if distance < minDistance {
minDistance = distance
result = word[j]
}
}
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var minDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = abs(i - j)
if distance < minDistance {
minDistance = distance
result = word[j]
}
}
}
}
}
return result
}
```
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if vowels.contains(word[j]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = word[j] // cannot assign value of type 'Character' to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel = ""
var closestDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = j - i
if distance < closestDistance {
closestVowel = word[j]
closestDistance = distance
}
}
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel = ""
var closestDistance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let distance = j - i
if distance < closestDistance {
closestVowel = word[j]
closestDistance = distance
}
}
}
}
}
return closestVowel
}
```
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if vowels.contains(word[j]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
closestVowel = word[j] // cannot assign value of type 'Character' to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel = ""
var closestDistance = Int.max
for (index, letter) in word.enumerated() {
if vowels.contains(letter) {
if index > 0 {
let distance = abs(index - word.distance(from: word.startIndex, to: word.index(of: letter)))
if distance < closestDistance {
closestVowel = String(letter)
closestDistance = distance
}
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel = ""
var closestDistance = Int.max
for (index, letter) in word.enumerated() {
if vowels.contains(letter) {
if index > 0 {
let distance = abs(index - word.distance(from: word.startIndex, to: word.index(of: letter)))
if distance < closestDistance {
closestVowel = String(letter)
closestDistance = distance
}
}
}
}
return closestVowel
}
```
let distance = abs(index - word.distance(from: word.startIndex, to: word.index(of: letter))) // value of optional type 'String.Index?' must be unwrapped to a value of type 'String.Index'
func getClosestVowel(word: String) -> String {
var vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
if i < distance {
distance = i
result = String(word[i])
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
if i < distance {
distance = i
result = String(word[i])
}
}
}
return result
}
```
var vowels = "aeiou" // variable 'vowels' was never mutated; consider changing to 'let' constant
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = String(word[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance = newDistance
result = word[j]
}
}
}
}
}
return result
}
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var result = ""
var distance = Int.max
for i in 0..<word.count {
if vowels.contains(word[i]) {
for j in i+1..<word.count {
if vowels.contains(word[j]) {
let newDistance = abs(i - j)
if newDistance < distance {
distance
if vowels.contains(word[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if vowels.contains(word[j]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = word[j] // cannot assign value of type 'Character' to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let word = word.lowercased()
var result = ""
for i in 0..<word.count {
if vowels.contains(String(word[word.index(word.startIndex, offsetBy: i)])) {
result = String(word[word.index(word.startIndex, offsetBy: i)])
break
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let word = word.lowercased()
var result = ""
for i in 0..<word.count {
if vowels.contains(String(word[word.index(word.startIndex, offsetBy: i)])) {
result = String(word[word.index(word.startIndex, offsetBy: i)])
break
}
}
return result
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
var minDistance = Int.max
for (index, char) in word.enumerated() {
if vowels.contains(String(char)) {
let distance = word.distance(from: word.startIndex, to: word.index(word.startIndex, offsetBy: index))
if distance < minDistance {
minDistance = distance
result = String(char)
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
var minDistance = Int.max
for (index, char) in word.enumerated() {
if vowels.contains(String(char)) {
let distance = word.distance(from: word.startIndex, to: word.index(word.startIndex, offsetBy: index))
if distance < minDistance {
minDistance = distance
result = String(char)
}
}
}
return result
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
if str == ")" {
if stack.isEmpty {
return "No"
}
stack.popLast()
} else {
stack.append(str)
}
}
return stack.isEmpty? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
if str == ")" {
if stack.isEmpty {
return "No"
}
stack.popLast()
} else {
stack.append(str)
}
}
return stack.isEmpty? "Yes" : "No"
}
```
stack.popLast() // result of call to 'popLast()' is unused
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for s in lst {
if s == ")" {
if stack.count == 0 {
return "No"
}
stack.popLast()
} else {
stack.append(s)
}
}
return stack.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 stack = [String]()
for s in lst {
if s == ")" {
if stack.count == 0 {
return "No"
}
stack.popLast()
} else {
stack.append(s)
}
}
return stack.count == 0? "Yes" : "No"
}
```
stack.popLast() // result of call to 'popLast()' is unused
return stack.count == 0? "Yes" : "No" // expected expression
return stack.count == 0? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Int'
return stack.count == 0? "Yes" : "No" // cannot convert return expression of type 'Bool' to return type 'String'
return stack.count == 0? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.count == 0? "Yes" : "No" // string literal is unused
return stack.count == 0? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for s in lst {
if s == ")" {
if stack.count == 0 {
return "No"
}
stack.removeLast()
} else {
stack.append(s)
}
}
return stack.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 stack = [String]()
for s in lst {
if s == ")" {
if stack.count == 0 {
return "No"
}
stack.removeLast()
} else {
stack.append(s)
}
}
return stack.count == 0? "Yes" : "No"
}
```
return stack.count == 0? "Yes" : "No" // expected expression
return stack.count == 0? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Int'
return stack.count == 0? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.count == 0? "Yes" : "No" // cannot convert return expression of type 'Bool' to return type 'String'
return stack.count == 0? "Yes" : "No" // string literal is unused
return stack.count == 0? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func matchParens(lst: [String]) -> String {
var stack = [Character]()
for c in lst[0] {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
for c in lst[1] {
if c == ")" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [Character]()
for c in lst[0] {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
for c in lst[1] {
if c == ")" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
stack.removeLast()
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // expected expression
func matchParens(lst: [String]) -> String {
var stack = [String]()
for s in lst {
if s == ")" {
if stack.count == 0 {
return "No"
}
stack.removeLast()
} else {
stack.append(s)
}
}
return stack.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 stack = [String]()
for s in lst {
if s == ")" {
if stack.count == 0 {
return "No"
}
stack.removeLast()
} else {
stack.append(s)
}
}
return stack.count == 0? "Yes" : "No"
}
```
return stack.count == 0? "Yes" : "No" // expected expression
return stack.count == 0? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Int'
return stack.count == 0? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.count == 0? "Yes" : "No" // cannot convert return expression of type 'Bool' to return type 'String'
return stack.count == 0? "Yes" : "No" // string literal is unused
return stack.count == 0? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == ")" {
if stack.isEmpty {
return "No"
}
stack.removeLast()
} else {
stack.append(i)
}
}
return stack.isEmpty? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == ")" {
if stack.isEmpty {
return "No"
}
stack.removeLast()
} else {
stack.append(i)
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
if str == ")" {
if stack.isEmpty {
return "No"
}
stack.removeLast()
} else {
stack.append(str)
}
}
return stack.isEmpty? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
if str == ")" {
if stack.isEmpty {
return "No"
}
stack.removeLast()
} else {
stack.append(str)
}
}
return stack.isEmpty? "Yes" : "No"
}
```
return stack.isEmpty? "Yes" : "No" // string literal is unused
return stack.isEmpty? "Yes" : "No" // expected expression
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return stack.isEmpty? "Yes" : "No" // cannot use optional chaining on non-optional value of type 'Bool'
func matchParens(lst: [String]) -> String {
var open = 0
var close = 0
for i in lst {
if i == "(" {
open += 1
} else {
close += 1
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var open = 0
var close = 0
for i in lst {
if i == "(" {
open += 1
} else {
close += 1
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
// TODO: Implement this function
return ""
}
```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 {
// TODO: Implement this function
return ""
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [Character]()
for c in lst[0] {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
stack.popLast()
}
}
if stack.isEmpty {
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 {
var stack = [Character]()
for c in lst[0] {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
stack.popLast()
}
}
if stack.isEmpty {
return "Yes"
}
return "No"
}
```
stack.popLast() // result of call to 'popLast()' is unused
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap<Int>(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap<Int>(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap<Int>(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap<Int>(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek()! {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek()! {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap<Int>(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap<Int>(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap<Int>(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap<Int>(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
var maxIndex = 0
var min = 0
var minIndex = 0
var min2 = 0
var min2Index = 0
for i in 0..<k {
result.append(arr[i])
}
for i in k..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
for i in 0..<k {
if result[i] < max {
result[i] = max
max = result[i]
maxIndex = i
}
}
for i in k..<arr.count {
if arr[i] > min {
min = arr[i]
minIndex = i
}
}
for i in 0..<k {
if result[i] < min {
result[i] = min
min = result[i]
minIndex = i
}
}
for i in k..<arr.count {
if arr[i] > min2 {
min2 = arr[i]
min2Index = i
}
}
for i in 0..<k {
if result[i] < min2 {
result[i] = min2
min2 = result[i]
min2Index = 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 max = 0
var maxIndex = 0
var min = 0
var minIndex = 0
var min2 = 0
var min2Index = 0
for i in 0..<k {
result.append(arr[i])
}
for i in k..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
for i in 0..<k {
if result[i] < max {
result[i] = max
max = result[i]
maxIndex = i
}
}
for i in k..<arr.count {
if arr[i] > min {
min = arr[i]
minIndex = i
}
}
for i in 0..<k {
if result[i] < min {
result[i] = min
min = result[i]
minIndex = i
}
}
for i in k..<arr.count {
if arr[i] > min2 {
min2 = arr[i]
min2Index = i
}
}
for i in 0..<k {
if result[i] < min2 {
result[i] = min2
min2 = result[i]
min2Index = i
}
}
return result
}
```
var maxIndex = 0 // variable 'maxIndex' was written to, but never read
var minIndex = 0 // variable 'minIndex' was written to, but never read
var min2Index = 0 // variable 'min2Index' was written to, but never read
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap<Int>(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap<Int>(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```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 maxHeap = Heap<Int>(sort:.max)
for i in 0..<k {
maxHeap.insert(arr[i])
}
for i in k..<arr.count {
if arr[i] > maxHeap.peek() {
maxHeap.remove()
maxHeap.insert(arr[i])
}
}
return maxHeap.array
}
```
var maxHeap = Heap<Int>(sort:.max) // cannot infer contextual base in reference to member 'max'
var maxHeap = Heap<Int>(sort:.max) // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
var maxIndex = 0
var min = 0
var minIndex = 0
var min2 = 0
var min2Index = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
result.append(max)
for i in 0..<arr.count {
if arr[i] > min && arr[i] < max {
min = arr[i]
minIndex = i
}
}
result.append(min)
for i in 0..<arr.count {
if arr[i] > min2 && arr[i] < min {
min2 = arr[i]
min2Index = i
}
}
result.append(min2)
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 max = 0
var maxIndex = 0
var min = 0
var minIndex = 0
var min2 = 0
var min2Index = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
result.append(max)
for i in 0..<arr.count {
if arr[i] > min && arr[i] < max {
min = arr[i]
minIndex = i
}
}
result.append(min)
for i in 0..<arr.count {
if arr[i] > min2 && arr[i] < min {
min2 = arr[i]
min2Index = i
}
}
result.append(min2)
return result
}
```
var maxIndex = 0 // variable 'maxIndex' was written to, but never read
var minIndex = 0 // variable 'minIndex' was written to, but never read
var min2Index = 0 // variable 'min2Index' was written to, but never read
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var k = k
var maxArr = [Int]()
var max = 0
var index = 0
while k > 0 {
max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
index = i
}
}
maxArr.append(max)
arr[index] = 0
k -= 1
}
return maxArr
}
```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
var k = k
var maxArr = [Int]()
var max = 0
var index = 0
while k > 0 {
max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
index = i
}
}
maxArr.append(max)
arr[index] = 0
k -= 1
}
return maxArr
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) { (result, element) in
if element.offset % 2 == 0 {
return result
}
return result + element.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().reduce(0) { (result, element) in
if element.offset % 2 == 0 {
return result
}
return result + element.element
}
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$1.offset % 2 == 1? $0 + $1.element : $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().reduce(0) {
$1.offset % 2 == 1? $0 + $1.element : $0
}
}
```
$1.offset % 2 == 1? $0 + $1.element : $0 // expected expression
$1.offset % 2 == 1? $0 + $1.element : $0 // cannot use optional chaining on non-optional value of type 'Int'
$1.offset % 2 == 1? $0 + $1.element : $0 // consecutive statements on a line must be separated by ';'
$1.offset % 2 == 1? $0 + $1.element : $0 // consecutive statements on a line must be separated by ';'
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 1? $1.element : 0)
}
}
```
$0 + ($1.offset % 2 == 1? $1.element : 0) // expected ',' separator
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot convert value of type '(Bool, Int)' to expected argument type 'Int'
$0 + ($1.offset % 2 == 1? $1.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) { (result, element) in
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 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().reduce(0) { (result, element) in
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0)
}
}
```
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // cannot convert value of type '((), Int)' to expected argument type 'Int'
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // '=' must have consistent whitespace on both sides
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // '=' must have consistent whitespace on both sides
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // cannot force unwrap value of non-optional type 'Int'
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // cannot use optional chaining on non-optional value of type 'Int'
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // expression is not assignable: '&&' returns immutable value
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // expression is not assignable: binary operator returns immutable value
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // cannot force unwrap value of non-optional type 'Int'
return result + (element.offset % 2!= 0 && element.element % 2!= 0? element.element : 0) // expected ',' separator
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 0 && $1.element.isOdd? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 0 && $1.element.isOdd? $1.element : 0)
}
}
```
return lst.enumerated().reduce(0) { // the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
$0 + ($1.offset % 2 == 0 && $1.element.isOdd? $1.element : 0) // expected ',' separator
func solution(lst: [Int]) -> Int {
return lst.enumerated().reduce(0) {
$0 + ($1.offset % 2 == 0 && $1.element.isOdd? $1.element : 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().reduce(0) {
$0 + ($1.offset % 2 == 0 && $1.element.isOdd? $1.element : 0)
}
}
```
return lst.enumerated().reduce(0) { // the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
$0 + ($1.offset % 2 == 0 && $1.element.isOdd? $1.element : 0) // expected ',' separator
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if String(arr[i]).count <= 2 {
sum += arr[i]
count += 1
}
}
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
var count = 0
for i in 0..<k {
if String(arr[i]).count <= 2 {
sum += arr[i]
count += 1
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
}
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
let num = arr[i]
if num < 10 {
sum += num
count += 1
} else if num < 100 {
sum += num
count += 1
}
}
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
var count = 0
for i in 0..<k {
let num = arr[i]
if num < 10 {
sum += num
count += 1
} else if num < 100 {
sum += num
count += 1
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if String(arr[i]).count <= 2 {
sum += arr[i]
count += 1
}
}
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
var count = 0
for i in 0..<k {
if String(arr[i]).count <= 2 {
sum += arr[i]
count += 1
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
} else if arr[i] < 100 {
sum += arr[i]
count += 2
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
}
}
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
var count = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
count += 1
}
}
return sum
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = 3 * num + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num /= 2
} else {
num = 3 * num + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(num)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(num)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current!= 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = 3 * current + 1
}
if current % 2!= 0 {
result.append(current)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current!= 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = 3 * current + 1
}
if current % 2!= 0 {
result.append(current)
}
}
result.append(1)
return result
}
```
while current!= 1 { // '=' must have consistent whitespace on both sides
while current!= 1 { // cannot force unwrap value of non-optional type 'Int'
while current!= 1 { // use of '=' in a boolean context, did you mean '=='?
if current % 2!= 0 { // '=' must have consistent whitespace on both sides
if current % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if current % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if current % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var temp = n
while temp!= 1 {
if temp % 2 == 0 {
temp = temp / 2
} else {
temp = (3 * temp) + 1
}
if temp % 2!= 0 {
result.append(temp)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var temp = n
while temp!= 1 {
if temp % 2 == 0 {
temp = temp / 2
} else {
temp = (3 * temp) + 1
}
if temp % 2!= 0 {
result.append(temp)
}
}
result.append(1)
return result
}
```
while temp!= 1 { // '=' must have consistent whitespace on both sides
while temp!= 1 { // cannot force unwrap value of non-optional type 'Int'
while temp!= 1 { // use of '=' in a boolean context, did you mean '=='?
if temp % 2!= 0 { // '=' must have consistent whitespace on both sides
if temp % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if temp % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if temp % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(num)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(num)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(num)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(num)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num!= 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2!= 0 {
result.append(num)
}
}
result.append(1)
return result
}
```
while num!= 1 { // use of '=' in a boolean context, did you mean '=='?
while num!= 1 { // '=' must have consistent whitespace on both sides
while num!= 1 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```
return date!= nil // use of '=' in a boolean context, did you mean '=='?
return date!= nil // cannot assign through '!': 'date' is a 'let' constant
return date!= nil // 'nil' cannot be assigned to type 'Date'
return date!= nil // '=' must have consistent whitespace on both sides
func validDate(date: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```
return date!= nil // use of '=' in a boolean context, did you mean '=='?
return date!= nil // cannot assign through '!': 'date' is a 'let' constant
return date!= nil // 'nil' cannot be assigned to type 'Date'
return date!= nil // '=' must have consistent whitespace on both sides
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```
return date!= nil // use of '=' in a boolean context, did you mean '=='?
return date!= nil // cannot assign through '!': 'date' is a 'let' constant
return date!= nil // 'nil' cannot be assigned to type 'Date'
return date!= nil // '=' must have consistent whitespace on both sides
func validDate(date: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
return date!= nil
}
```
return date!= nil // use of '=' in a boolean context, did you mean '=='?
return date!= nil // cannot assign through '!': 'date' is a 'let' constant
return date!= nil // 'nil' cannot be assigned to type 'Date'
return date!= nil // '=' must have consistent whitespace on both sides
func validDate(date: String) -> Bool {
return false
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
return false
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
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 {
return true
}
```
// XCTAssertTrue failed
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
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> {
return.success(txt.split(separator: " ").map(String.init))
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map(String.init))
}
splitWords(txt: "Hello world!")
splitWords(txt: "Hello,world!")
splitWords(txt: "abcdef")
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
splitWords(txt: "Hello world!") ==.success(["Hello", "world!"])
splitWords(txt: "Hello,world!") ==.success(["Hello", "world!"])
splitWords(txt: "abcdef") ==.failure(3)
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: ",").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.filter { $0.isLowercase }.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> {
return.success(txt.split(separator: " ").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: ",").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.filter { $0.isLowercase }.count)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
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> {
return.success(txt.split(separator: " ").map(String.init))
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map(String.init))
}
splitWords(txt: "Hello world!") ==.success(["Hello", "world!"])
splitWords(txt: "Hello,world!") ==.success(["Hello", "world!"])
splitWords(txt: "abcdef") ==.failure(3)
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: ",").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 })
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: ",").map { String($0) })
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 })
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // binary operator '+' cannot be applied to operands of type 'Int' and 'Bool?'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // expected expression
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // cannot use optional chaining on non-optional value of type 'Bool'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: ",").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 })
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: " ").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.split(separator: ",").map(String.init))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 })
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // binary operator '+' cannot be applied to operands of type 'Int' and 'Bool?'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // expected expression
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return.failure(txt.reduce(0) { $0 + $1.isLowercase? 1 : 0 }) // cannot use optional chaining on non-optional value of type 'Bool'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.components(separatedBy: " "))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.components(separatedBy: ","))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.filter { $0.isLowercase }.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> {
return.success(txt.components(separatedBy: " "))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.success(txt.components(separatedBy: ","))
}
func splitWords(txt: String) -> Result<[String], Int> {
return.failure(txt.filter { $0.isLowercase }.count)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
func isSorted(lst: [Int]) -> Bool {
// TODO: Write your code here
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 {
// TODO: Write your code here
return false
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
// TODO: Implement this function
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 {
// TODO: Implement this function
return true
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = 0
for i in 0..<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 = 0
for i in 0..<lst.count {
if lst[i] < last {
sorted = false
break
}
last = lst[i]
}
return sorted
}
```
// 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 prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
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 prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
sorted = false
break
}
prev = 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 prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
sorted = false
break
}
prev = lst[i]
}
return sorted
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
guard lst.count > 1 else { return true }
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev { return false }
prev = lst[i]
}
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 {
guard lst.count > 1 else { return true }
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev { return false }
prev = lst[i]
}
return true
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
for i in 0..<lst.count-1 {
if lst[i] > lst[i+1] {
return false
}
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
for i in 0..<lst.count-1 {
if lst[i] > lst[i+1] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
sorted = false
}
prev = 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 prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
sorted = false
}
prev = lst[i]
}
return sorted
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var previous = 0
for i in lst {
if i < previous {
sorted = false
}
previous = 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 = 0
for i in lst {
if i < previous {
sorted = false
}
previous = i
}
return sorted
}
```
// 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)
return (start..<end).contains(start)? "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
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
return (start..<end).contains(start)? "YES" : "NO"
}
```
return (start..<end).contains(start)? "YES" : "NO" // string literal is unused
return (start..<end).contains(start)? "YES" : "NO" // expected expression
return (start..<end).contains(start)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return (start..<end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start..<end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return start < end? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return start < end? "YES" : "NO"
}
```
return start < end? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return start < end? "YES" : "NO" // cannot convert return expression of type 'Bool' to return type 'String'
return start < end? "YES" : "NO" // string literal is unused
return start < end? "YES" : "NO" // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return start < end? "YES" : "NO" // expected expression
return start < end? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Int'
return start < end? "YES" : "NO" // consecutive statements on a line must be separated by ';'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
guard n!= 2 else { return true }
guard n % 2!= 0 else { return false }
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
return isPrime(end - start + 1)? "YES" : "NO"
}
func isPrime(_ n: Int) -> Bool {
guard n > 1 else { return false }
guard n!= 2 else { return true }
guard n % 2!= 0 else { return false }
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // expected expression
return isPrime(end - start + 1)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return isPrime(end - start + 1)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return isPrime(end - start + 1)? "YES" : "NO" // string literal is unused
guard n!= 2 else { return true } // cannot force unwrap value of non-optional type 'Int'
guard n!= 2 else { return true } // '=' must have consistent whitespace on both sides
guard n!= 2 else { return true } // use of '=' in a boolean context, did you mean '=='?
guard n % 2!= 0 else { return false } // '=' must have consistent whitespace on both sides
guard n % 2!= 0 else { return false } // use of '=' in a boolean context, did you mean '=='?
guard n % 2!= 0 else { return false } // cannot force unwrap value of non-optional type 'Int'
guard n % 2!= 0 else { return false } // expression is not assignable: binary operator returns immutable value
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
return "\(max(start1, start2)) \(min(end1, end2))"
}
```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"
}
return "\(max(start1, start2)) \(min(end1, end2))"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).contains(start)? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).contains(start)? "YES" : "NO"
}
```
return (start...end).contains(start)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return (start...end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).contains(start)? "YES" : "NO" // string literal is unused
return (start...end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).contains(start)? "YES" : "NO" // expected expression
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
return "\(max(start1, start2)) \(min(end1, end2))"
}
```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"
}
return "\(max(start1, start2)) \(min(end1, end2))"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).contains(start)? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).contains(start)? "YES" : "NO"
}
```
return (start...end).contains(start)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return (start...end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).contains(start)? "YES" : "NO" // string literal is unused
return (start...end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).contains(start)? "YES" : "NO" // expected expression
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO"
}
```
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO" // cannot convert return expression of type 'Bool' to return type 'String'
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Int'
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO" // expected expression
return (max(start1, start2)..<min(end1, end2)).count == 1? "YES" : "NO" // string literal is unused
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
return "\(max(start1, start2)) \(min(end1, end2))"
}
```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"
}
return "\(max(start1, start2)) \(min(end1, end2))"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).contains(start)? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
return (start...end).contains(start)? "YES" : "NO"
}
```
return (start...end).contains(start)? "YES" : "NO" // cannot use optional chaining on non-optional value of type 'Bool'
return (start...end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).contains(start)? "YES" : "NO" // string literal is unused
return (start...end).contains(start)? "YES" : "NO" // consecutive statements on a line must be separated by ';'
return (start...end).contains(start)? "YES" : "NO" // expected expression
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num < 0? -1 : 1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num < 0? -1 : 1
}
return result
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
result *= num < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
result *= num < 0? -1 : 1 // cannot convert value of type 'Bool' to expected argument type 'Int'
result *= num < 0? -1 : 1 // cannot use optional chaining on non-optional value of type 'Int'
result *= num < 0? -1 : 1 // integer literal is unused
result *= num < 0? -1 : 1 // expected expression
result *= num < 0? -1 : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result *= num < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
return arr.reduce(1, { $0 * $1.sign })
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
return arr.reduce(1, { $0 * $1.sign })
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
return arr.reduce(1, { $0 * $1.sign }) // value of type 'Int' has no member 'sign'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
return arr.reduce(1, { $0 * $1.sign })
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
return arr.reduce(1, { $0 * $1.sign })
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
return arr.reduce(1, { $0 * $1.sign }) // value of type 'Int' has no member 'sign'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
return arr.reduce(1, { $0 * $1.sign })
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
return arr.reduce(1, { $0 * $1.sign })
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
return arr.reduce(1, { $0 * $1.sign }) // value of type 'Int' has no member 'sign'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num < 0? -1 : 1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num < 0? -1 : 1
}
return result
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
result *= num < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
result *= num < 0? -1 : 1 // cannot convert value of type 'Bool' to expected argument type 'Int'
result *= num < 0? -1 : 1 // cannot use optional chaining on non-optional value of type 'Int'
result *= num < 0? -1 : 1 // integer literal is unused
result *= num < 0? -1 : 1 // expected expression
result *= num < 0? -1 : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result *= num < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for i in arr {
result *= i < 0? -1 : 1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for i in arr {
result *= i < 0? -1 : 1
}
return result
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
result *= i < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
result *= i < 0? -1 : 1 // cannot use optional chaining on non-optional value of type 'Int'
result *= i < 0? -1 : 1 // integer literal is unused
result *= i < 0? -1 : 1 // cannot convert value of type 'Bool' to expected argument type 'Int'
result *= i < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
result *= i < 0? -1 : 1 // expected expression
result *= i < 0? -1 : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num.sign
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num.sign
}
return result
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
result *= num.sign // value of type 'Int' has no member 'sign'
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for i in arr {
result *= i < 0? -1 : 1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard!arr.isEmpty else { return nil }
var result = 1
for i in arr {
result *= i < 0? -1 : 1
}
return result
}
```
guard!arr.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
result *= i < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
result *= i < 0? -1 : 1 // cannot use optional chaining on non-optional value of type 'Int'
result *= i < 0? -1 : 1 // integer literal is unused
result *= i < 0? -1 : 1 // cannot convert value of type 'Bool' to expected argument type 'Int'
result *= i < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
result *= i < 0? -1 : 1 // expected expression
result *= i < 0? -1 : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var result = 1
for i in 0..<arr.count {
result *= arr[i] * sign(arr[i])
}
return result
}
func sign(_ n: Int) -> Int {
return n < 0? -1 : 1
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var result = 1
for i in 0..<arr.count {
result *= arr[i] * sign(arr[i])
}
return result
}
func sign(_ n: Int) -> Int {
return n < 0? -1 : 1
}
```
return n < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
return n < 0? -1 : 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return n < 0? -1 : 1 // integer literal is unused
return n < 0? -1 : 1 // cannot convert return expression of type 'Bool' to return type 'Int'
return n < 0? -1 : 1 // expected expression
return n < 0? -1 : 1 // cannot use optional chaining on non-optional value of type 'Int'
return n < 0? -1 : 1 // consecutive statements on a line must be separated by ';'
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var positive = 0
var negative = 0
for num in arr {
if num == 0 {
product *= 0
} else if num > 0 {
positive += 1
} else {
negative += 1
}
}
return product * positive * negative
}
```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 product = 1
var positive = 0
var negative = 0
for num in arr {
if num == 0 {
product *= 0
} else if num > 0 {
positive += 1
} else {
negative += 1
}
}
return product * positive * negative
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathSum = Int.max
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int, Int)]()
queue.append((0, 0, 0))
visited[0][0] = true
while!queue.isEmpty {
let (row, col, pathSum) = queue.removeFirst()
if pathSum == k {
minPath = [Int]()
minPathSum = pathSum
for (i, j) in queue {
minPath.append(grid[i][j])
}
break
}
if row > 0 {
if!visited[row - 1][col] {
visited[row - 1][col] = true
queue.append((row - 1, col, pathSum + grid[row - 1][col]))
}
}
if col > 0 {
if!visited[row][col - 1] {
visited[row][col - 1] = true
queue.append((row, col - 1, pathSum + grid[row][col - 1]))
}
}
if row < grid.count - 1 {
if!visited[row + 1][col] {
visited[row + 1][col] = true
queue.append((row + 1, col, pathSum + grid[row + 1][col]))
}
}
if col < grid[0].count - 1 {
if!visited[row][col + 1] {
visited[row][col + 1] = true
queue.append((row, col + 1, pathSum + grid[row][col + 1]))
}
}
}
return minPath
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathSum = Int.max
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int, Int)]()
queue.append((0, 0, 0))
visited[0][0] = true
while!queue.isEmpty {
let (row, col, pathSum) = queue.removeFirst()
if pathSum == k {
minPath = [Int]()
minPathSum = pathSum
for (i, j) in queue {
minPath.append(grid[i][j])
}
break
}
if row > 0 {
if!visited[row - 1][col] {
visited[row - 1][col] = true
queue.append((row - 1, col, pathSum + grid[row - 1][col]))
}
}
if col > 0 {
if!visited[row][col - 1] {
visited[row][col - 1] = true
queue.append((row, col - 1, pathSum + grid[row][col - 1]))
}
}
if row < grid.count - 1 {
if!visited[row + 1][col] {
visited[row + 1][col] = true
queue.append((row + 1, col, pathSum + grid[row + 1][col]))
}
}
if col < grid[0].count - 1 {
if!visited[row][col + 1] {
visited[row][col + 1] = true
queue.append((row, col + 1, pathSum + grid[row][col + 1]))
}
}
}
return minPath
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathLength = Int.max
var minPathValues = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int, Int)]()
queue.append((0, 0, 0))
visited[0][0] = true
while!queue.isEmpty {
let (x, y, pathLength) = queue.removeFirst()
if pathLength == k {
minPath = minPathValues
minPathLength = pathLength
break
}
let directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for direction in directions {
let newX = x + direction.0
let newY = y + direction.1
if newX >= 0 && newX < grid.count && newY >= 0 && newY < grid[0].count &&!visited[newX][newY] {
visited[newX][newY] = true
queue.append((newX, newY, pathLength + 1))
minPathValues.append(grid[newX][newY])
}
}
}
return minPath
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathLength = Int.max
var minPathValues = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int, Int)]()
queue.append((0, 0, 0))
visited[0][0] = true
while!queue.isEmpty {
let (x, y, pathLength) = queue.removeFirst()
if pathLength == k {
minPath = minPathValues
minPathLength = pathLength
break
}
let directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for direction in directions {
let newX = x + direction.0
let newY = y + direction.1
if newX >= 0 && newX < grid.count && newY >= 0 && newY < grid[0].count &&!visited[newX][newY] {
visited[newX][newY] = true
queue.append((newX, newY, pathLength + 1))
minPathValues.append(grid[newX][newY])
}
}
}
return minPath
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathSum = Int.max
var path = [Int]()
var pathSum = 0
var grid = grid
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
func dfs(row: Int, col: Int, pathSum: Int, path: [Int]) {
if row < 0 || row >= grid.count || col < 0 || col >= grid[0].count || visited[row][col] {
return
}
visited[row][col] = true
path.append(grid[row][col])
pathSum += grid[row][col]
if pathSum >= minPathSum {
return
}
if path.count == k {
if pathSum < minPathSum {
minPathSum = pathSum
minPath = path
}
return
}
dfs(row: row - 1, col: col, pathSum: pathSum, path: path)
dfs(row: row + 1, col: col, pathSum: pathSum, path: path)
dfs(row: row, col: col - 1, pathSum: pathSum, path: path)
dfs(row: row, col: col + 1, pathSum: pathSum, path: path)
visited[row][col] = false
}
dfs(row: 0, col: 0, pathSum: 0, path: path)
return minPath
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathSum = Int.max
var path = [Int]()
var pathSum = 0
var grid = grid
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
func dfs(row: Int, col: Int, pathSum: Int, path: [Int]) {
if row < 0 || row >= grid.count || col < 0 || col >= grid[0].count || visited[row][col] {
return
}
visited[row][col] = true
path.append(grid[row][col])
pathSum += grid[row][col]
if pathSum >= minPathSum {
return
}
if path.count == k {
if pathSum < minPathSum {
minPathSum = pathSum
minPath = path
}
return
}
dfs(row: row - 1, col: col, pathSum: pathSum, path: path)
dfs(row: row + 1, col: col, pathSum: pathSum, path: path)
dfs(row: row, col: col - 1, pathSum: pathSum, path: path)
dfs(row: row, col: col + 1, pathSum: pathSum, path: path)
visited[row][col] = false
}
dfs(row: 0, col: 0, pathSum: 0, path: path)
return minPath
}
```
path.append(grid[row][col]) // cannot use mutating member on immutable value: 'path' is a 'let' constant
pathSum += grid[row][col] // left side of mutating operator isn't mutable: 'pathSum' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [Cell]()
var minPathLength = 0
var minPath = [Int]()
visited[0][0] = true
queue.append(Cell(row: 0, column: 0))
while!queue.isEmpty {
let cell = queue.removeFirst()
let row = cell.row
let column = cell.column
if row == grid.count - 1 && column == grid[0].count - 1 {
minPathLength = visited[row][column]
minPath = visited[row][column]
break
}
if row + 1 < grid.count &&!visited[row + 1][column] {
visited[row + 1][column] = visited[row][column] + 1
queue.append(Cell(row: row + 1, column: column))
}
if column + 1 < grid[0].count &&!visited[row][column + 1] {
visited[row][column + 1] = visited[row][column] + 1
queue.append(Cell(row: row, column: column + 1))
}
}
var row = 0
var column = 0
var path = [Int]()
while minPathLength > 0 {
path.append(grid[row][column])
minPathLength -= 1
if row + 1 < grid.count && visited[row + 1][column] == minPathLength {
row += 1
} else if column + 1 < grid[0].count && visited[row][column + 1] == minPathLength {
column += 1
}
}
return path
}
struct Cell {
var row: Int
var column: 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] {
var minPath = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [Cell]()
var minPathLength = 0
var minPath = [Int]()
visited[0][0] = true
queue.append(Cell(row: 0, column: 0))
while!queue.isEmpty {
let cell = queue.removeFirst()
let row = cell.row
let column = cell.column
if row == grid.count - 1 && column == grid[0].count - 1 {
minPathLength = visited[row][column]
minPath = visited[row][column]
break
}
if row + 1 < grid.count &&!visited[row + 1][column] {
visited[row + 1][column] = visited[row][column] + 1
queue.append(Cell(row: row + 1, column: column))
}
if column + 1 < grid[0].count &&!visited[row][column + 1] {
visited[row][column + 1] = visited[row][column] + 1
queue.append(Cell(row: row, column: column + 1))
}
}
var row = 0
var column = 0
var path = [Int]()
while minPathLength > 0 {
path.append(grid[row][column])
minPathLength -= 1
if row + 1 < grid.count && visited[row + 1][column] == minPathLength {
row += 1
} else if column + 1 < grid[0].count && visited[row][column + 1] == minPathLength {
column += 1
}
}
return path
}
struct Cell {
var row: Int
var column: Int
}
```
var minPath = [Int]() // invalid redeclaration of 'minPath'
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
if row + 1 < grid.count && visited[row + 1][column] == minPathLength { // binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'
} else if column + 1 < grid[0].count && visited[row][column + 1] == minPathLength { // binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathLength = Int.max
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int, Int)]()
queue.append((0, 0, 0))
visited[0][0] = true
while!queue.isEmpty {
let (x, y, length) = queue.removeFirst()
if length == k {
minPath = [Int]()
minPath.append(grid[x][y])
minPathLength = length
break
}
if x > 0 &&!visited[x - 1][y] {
visited[x - 1][y] = true
queue.append((x - 1, y, length + 1))
}
if y > 0 &&!visited[x][y - 1] {
visited[x][y - 1] = true
queue.append((x, y - 1, length + 1))
}
if x < grid.count - 1 &&!visited[x + 1][y] {
visited[x + 1][y] = true
queue.append((x + 1, y, length + 1))
}
if y < grid[0].count - 1 &&!visited[x][y + 1] {
visited[x][y + 1] = true
queue.append((x, y + 1, length + 1))
}
}
var i = 0
while i < minPath.count {
var j = i + 1
while j < minPath.count {
if minPath[i] > minPath[j] {
minPath.swapAt(i, j)
}
j += 1
}
i += 1
}
return minPath
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var minPath = [Int]()
var minPathLength = Int.max
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [(Int, Int, Int)]()
queue.append((0, 0, 0))
visited[0][0] = true
while!queue.isEmpty {
let (x, y, length) = queue.removeFirst()
if length == k {
minPath = [Int]()
minPath.append(grid[x][y])
minPathLength = length
break
}
if x > 0 &&!visited[x - 1][y] {
visited[x - 1][y] = true
queue.append((x - 1, y, length + 1))
}
if y > 0 &&!visited[x][y - 1] {
visited[x][y - 1] = true
queue.append((x, y - 1, length + 1))
}
if x < grid.count - 1 &&!visited[x + 1][y] {
visited[x + 1][y] = true
queue.append((x + 1, y, length + 1))
}
if y < grid[0].count - 1 &&!visited[x][y + 1] {
visited[x][y + 1] = true
queue.append((x, y + 1, length + 1))
}
}
var i = 0
while i < minPath.count {
var j = i + 1
while j < minPath.count {
if minPath[i] > minPath[j] {
minPath.swapAt(i, j)
}
j += 1
}
i += 1
}
return minPath
}
```
while!queue.isEmpty { // expected expression, var, or let in 'while' condition
```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 minPath = [Int]()
var minPathLength = Int.max
var minPathValues = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [[Int]]()
var queueLength = 0
var queueValues = [Int]()
var queueVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedLength = 0
var queueVisitedValues = [Int]()
var queueVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedLength = 0
var queueVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedLength = 0
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedValues = [Int]()
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queueVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisitedVisited
```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 minPath = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [Int]()
var minPathLength = 0
var minPathValue = 0
var minPathIndex = 0
var minPathValues = [Int]()
var minPathValuesIndex = 0
var minPathValuesLength = 0
var minPathValuesCount = 0
var minPathValuesQueue = [Int]()
var minPathValuesQueueIndex = 0
var minPathValuesQueueLength = 0
var minPathValuesQueueCount = 0
var minPathValuesQueueValue = 0
var minPathValuesQueueValueIndex = 0
var minPathValuesQueueValueLength = 0
var minPathValuesQueueValueCount = 0
var minPathValuesQueueValueQueue = [Int]()
var minPathValuesQueueValueQueueIndex = 0
var minPathValuesQueueValueQueueLength = 0
var minPathValuesQueueValueQueueCount = 0
var minPathValuesQueueValueQueueValue = 0
var minPathValuesQueueValueQueueValueIndex = 0
var minPathValuesQueueValueQueueValueLength = 0
var minPathValuesQueueValueQueueValueCount = 0
var minPathValuesQueueValueQueueValueQueue = [Int]()
var minPathValuesQueueValueQueueValueQueueIndex = 0
var minPathValuesQueueValueQueueValueQueueLength = 0
var minPathValuesQueueValueQueueValueQueueCount = 0
var minPathValuesQueueValueQueueValueQueueValue = 0
var minPathValuesQueueValueQueueValueQueueValueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueLength = 0
var minPathValuesQueueValueQueueValueQueueValueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueue = [Int]()
var minPathValuesQueueValueQueueValueQueueValueQueueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValue = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueue = [Int]()
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValue = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueue = [Int]()
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValue = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueue = [Int]()
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueCount = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueValue = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueIndex = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueLength = 0
var minPathValuesQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueQueueValueCount = 0
```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 minPath = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [Cell]()
var minPathLength = Int.max
var minPathValues = [Int]()
var minPathValuesCount = 0
var minPathValuesIndex = 0
var minPathValuesCountIndex = 0
var minPathValuesIndexIndex = 0
var minPathValuesCountIndexIndex = 0
var minPathValuesIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesCountIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var minPathValuesIndexIndex
```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 minPath = [Int]()
var minPathSum = Int.max
var pathSum = 0
var path = [Int]()
var grid = grid
var visited = [[Bool]](repeating: [Bool](repeating: false, count: grid[0].count), count: grid.count)
var queue = [Int]()
var queueSum = 0
var queuePath = [Int]()
var queuePathSum = 0
var queuePathIndex = 0
var queuePathSumIndex = 0
var queuePathIndexIndex = 0
var queuePathSumIndexIndex = 0
var queuePathIndexIndexIndex = 0
var queuePathSumIndexIndexIndex = 0
var queuePathIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathSumIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex = 0
var queuePathIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndexIndex =
```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 minPath = [Int]()
var minPathLength = Int.max
var minPathValue = Int.max
var minPathValueIndex = 0
var minPathValueCount = 0
var minPathValueCountIndex = 0
var minPathValueCountValue = 0
var minPathValueCountValueIndex = 0
var minPathValueCountValueCount = 0
var minPathValueCountValueCountIndex = 0
var minPathValueCountValueCountValue = 0
var minPathValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCount = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountIndex = 0
var minPathValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValueCountValue = 0
var minPathValueCountValueCountValueCountValueCountValueCount
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(3)
if n == 0 {
return tri
}
tri.append(2)
if n == 1 {
return tri
}
tri.append(1)
if n == 2 {
return tri
}
for i in 3...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```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 tri = [Int]()
tri.append(3)
if n == 0 {
return tri
}
tri.append(2)
if n == 1 {
return tri
}
tri.append(1)
if n == 2 {
return tri
}
for i in 3...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(1)
tri.append(3)
if n == 0 {
return tri
}
if n == 1 {
return tri
}
if n == 2 {
return tri
}
for i in 3...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```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 tri = [Int]()
tri.append(1)
tri.append(3)
if n == 0 {
return tri
}
if n == 1 {
return tri
}
if n == 2 {
return tri
}
for i in 3...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(1)
tri.append(3)
if n == 0 {
return tri
}
if n == 1 {
return tri
}
if n == 2 {
return tri
}
for i in 3...n {
if i % 2 == 0 {
tri.append(tri[i-2] + tri[i-3])
} else {
tri.append(tri[i-1] + tri[i-2] + tri[i-3])
}
}
return tri
}
```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 tri = [Int]()
tri.append(1)
tri.append(3)
if n == 0 {
return tri
}
if n == 1 {
return tri
}
if n == 2 {
return tri
}
for i in 3...n {
if i % 2 == 0 {
tri.append(tri[i-2] + tri[i-3])
} else {
tri.append(tri[i-1] + tri[i-2] + tri[i-3])
}
}
return tri
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(1)
tri.append(1)
tri.append(2)
for i in 3...n {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
return tri
}
```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 tri = [Int]()
tri.append(1)
tri.append(1)
tri.append(2)
for i in 3...n {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
return tri
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(3)
for i in 1...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```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 tri = [Int]()
tri.append(3)
for i in 1...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(1)
tri.append(3)
if n == 0 {
return tri
}
for i in 2...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```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 tri = [Int]()
tri.append(1)
tri.append(3)
if n == 0 {
return tri
}
for i in 2...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var tri = [1, 3]
if n < 2 {
return tri
}
for i in 2...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```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 tri = [1, 3]
if n < 2 {
return tri
}
for i in 2...n {
if i % 2 == 0 {
tri.append(tri[i - 1] + tri[i - 2] / 2)
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
}
return tri
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(3)
if n == 0 {
return tri
}
tri.append(0)
if n == 1 {
return tri
}
tri.append(0)
if n == 2 {
return tri
}
for i in 3...n {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
if i % 2 == 0 {
tri[i] = tri[i] / 2
}
}
return tri
}
```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 tri = [Int]()
tri.append(3)
if n == 0 {
return tri
}
tri.append(0)
if n == 1 {
return tri
}
tri.append(0)
if n == 2 {
return tri
}
for i in 3...n {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
if i % 2 == 0 {
tri[i] = tri[i] / 2
}
}
return tri
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [Int]()
result.append(1)
if n == 0 {
return result
}
result.append(3)
if n == 1 {
return result
}
result.append(2)
if n == 2 {
return result
}
for i in 3...n {
if i % 2 == 0 {
result.append(result[i - 2] + result[i - 3])
} else {
result.append(result[i - 1] + result[i - 2] + result[i - 3])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [Int]()
result.append(1)
if n == 0 {
return result
}
result.append(3)
if n == 1 {
return result
}
result.append(2)
if n == 2 {
return result
}
for i in 3...n {
if i % 2 == 0 {
result.append(result[i - 2] + result[i - 3])
} else {
result.append(result[i - 1] + result[i - 2] + result[i - 3])
}
}
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var tri = [Int]()
tri.append(1)
tri.append(1)
tri.append(3)
for i in 3...n {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
return tri
}
```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 tri = [Int]()
tri.append(1)
tri.append(1)
tri.append(3)
for i in 3...n {
tri.append(tri[i - 1] + tri[i - 2] + tri[i - 3])
}
return tri
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
for digit in String(n) {
if digit.isDigit && digit.isOdd {
result *= Int(digit)
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
for digit in String(n) {
if digit.isDigit && digit.isOdd {
result *= Int(digit)
}
}
return result
}
```
if digit.isDigit && digit.isOdd { // value of type 'Character' has no member 'isOdd'
if digit.isDigit && digit.isOdd { // value of type 'Character' has no member 'isDigit'
result *= Int(digit) // no exact matches in call to initializer
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= digit
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= digit
}
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var 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 {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2!= 0 {
result *= digit
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2!= 0 {
result *= digit
}
num /= 10
}
return result
}
```
if digit % 2!= 0 { // '=' must have consistent whitespace on both sides
if digit % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
for digit in String(n) {
if digit.isDigit {
result *= Int(digit)
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
for digit in String(n) {
if digit.isDigit {
result *= Int(digit)
}
}
return result
}
```
if digit.isDigit { // value of type 'Character' has no member 'isDigit'
result *= Int(digit) // no exact matches in call to initializer
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 isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
isNested(string: "[[]]")
isNested(string: "[]]]]]]][[[[[]")
isNested(string: "[][]")
isNested(string: "[]")
isNested(string: "[[][]]")
isNested(string: "[[]][[")
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
isNested(string: "[[]]")
isNested(string: "[]]]]]]][[[[[]")
isNested(string: "[][]")
isNested(string: "[]")
isNested(string: "[[][]]")
isNested(string: "[[]][[")
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append(String(char))
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append(String(char))
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append(String(char))
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append(String(char))
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
stack.append(char) // cannot convert value of type 'Character' to expected argument type 'String'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
isNested(string: "[[]]")
isNested(string: "[]]]]]]][[[[[]")
isNested(string: "[][]")
isNested(string: "[]")
isNested(string: "[[][]]")
isNested(string: "[[]][[")
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($0)) }.reduce(0, +) * lst.map { Int(ceil($0)) }.reduce(0, +)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($0)) }.reduce(0, +) * lst.map { Int(ceil($0)) }.reduce(0, +)
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($0)) }.reduce(0, +) * lst.map { Int(ceil($0)) }.reduce(0, +)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($0)) }.reduce(0, +) * lst.map { Int(ceil($0)) }.reduce(0, +)
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(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 { Int(ceil($0)) }.map { $0 * $0 }.reduce(0, +)
}
```
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!= nil && txt.last!.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 {
return txt.last!= nil && txt.last!.isLetter
}
```
return txt.last!= nil && txt.last!.isLetter // cannot assign through '!': 'last' is a get-only property
return txt.last!= nil && txt.last!.isLetter // '=' must have consistent whitespace on both sides
return txt.last!= nil && txt.last!.isLetter // cannot assign value of type 'Bool' to type 'String.Element' (aka 'Character')
return txt.last!= nil && txt.last!.isLetter // use of '=' in a boolean context, did you mean '=='?
return txt.last!= nil && txt.last!.isLetter // 'nil' is not compatible with expected argument type 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last?.isLetter == true && txt.last!= " "
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last?.isLetter == true && txt.last!= " "
}
```
return txt.last?.isLetter == true && txt.last!= " " // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'Bool'
return txt.last?.isLetter == true && txt.last!= " " // expression is not assignable: '&&' returns immutable value
return txt.last?.isLetter == true && txt.last!= " " // '=' must have consistent whitespace on both sides
return txt.last?.isLetter == true && txt.last!= " " // use of '=' in a boolean context, did you mean '=='?
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last == " " || txt.last == nil? false : true
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last == " " || txt.last == nil? false : true
}
```
return txt.last == " " || txt.last == nil? false : true // '?' must be followed by a call, member lookup, or subscript
return txt.last == " " || txt.last == nil? false : true // consecutive statements on a line must be separated by ';'
return txt.last == " " || txt.last == nil? false : true // boolean literal is unused
return txt.last == " " || txt.last == nil? false : true // consecutive statements on a line must be separated by ';'
return txt.last == " " || txt.last == nil? false : true // expected expression
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last?? " "
return lastChar.isLetter &&!lastChar.isWhitespace
}
```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 &&!lastChar.isWhitespace
}
```
let lastChar = txt.last?? " " // consecutive statements on a line must be separated by ';'
let lastChar = txt.last?? " " // string literal is unused
let lastChar = txt.last?? " " // cannot use optional chaining on non-optional value of type 'String.Element' (aka 'Character')
return lastChar.isLetter &&!lastChar.isWhitespace // consecutive statements on a line must be separated by ';'
return lastChar.isLetter &&!lastChar.isWhitespace // cannot find operator '&&!' in scope
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ")
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ")
}
```
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // cannot assign value of type 'Bool' to type 'String.Element' (aka 'Character')
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // use of '=' in a boolean context, did you mean '=='?
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // 'nil' is not compatible with expected argument type 'Bool'
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // consecutive statements on a line must be separated by ';'
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // cannot assign through '!': 'last' is a get-only property
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // '=' must have consistent whitespace on both sides
return txt.last!= nil && txt.last!.isLetter &&!txt.hasSuffix(" ") // cannot find operator '&&!' in scope
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
return lastChar.isLetter &&!lastChar.isWhitespace
}
```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 &&!lastChar.isWhitespace
}
```
return lastChar.isLetter &&!lastChar.isWhitespace // cannot find operator '&&!' in scope
return lastChar.isLetter &&!lastChar.isWhitespace // consecutive statements on a line must be separated by ';'
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace
}
```
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // consecutive statements on a line must be separated by ';'
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // cannot assign through '!': 'last' is a get-only property
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // '=' must have consistent whitespace on both sides
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // cannot assign value of type 'Bool' to type 'String.Element' (aka 'Character')
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // cannot find operator '&&!' in scope
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // 'nil' is not compatible with expected argument type 'Bool'
return txt.last!= nil && txt.last!.isLetter &&!txt.last!.isWhitespace // use of '=' in a boolean context, did you mean '=='?
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!= nil && txt.last!.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 {
return txt.last!= nil && txt.last!.isLetter
}
```
return txt.last!= nil && txt.last!.isLetter // cannot assign through '!': 'last' is a get-only property
return txt.last!= nil && txt.last!.isLetter // '=' must have consistent whitespace on both sides
return txt.last!= nil && txt.last!.isLetter // cannot assign value of type 'Bool' to type 'String.Element' (aka 'Character')
return txt.last!= nil && txt.last!.isLetter // use of '=' in a boolean context, did you mean '=='?
return txt.last!= nil && txt.last!.isLetter // 'nil' is not compatible with expected argument type 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last == nil || txt.last!.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 {
return txt.last == nil || txt.last!.isLetter
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last?.isLetter?? false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last?.isLetter?? false
}
```
return txt.last?.isLetter?? false // consecutive statements on a line must be separated by ';'
return txt.last?.isLetter?? false // cannot use optional chaining on non-optional value of type 'Bool'
return txt.last?.isLetter?? false // boolean literal is unused
return txt.last?.isLetter?? false // cannot use optional chaining on non-optional value of type 'Bool'
return txt.last?.isLetter?? false // optional type 'Bool?' cannot be used as a boolean; test for '!= nil' instead
func canArrange(arr: [Int]) -> Int {
var max = -1
var maxIndex = -1
for (index, value) in arr.enumerated() {
if value > max {
max = value
maxIndex = index
}
}
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 max = -1
var maxIndex = -1
for (index, value) in arr.enumerated() {
if value > max {
max = value
maxIndex = index
}
}
return maxIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
var prev = 0
for i in 0..<arr.count {
if i > 0 && arr[i] <= prev {
result = i
break
}
prev = arr[i]
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var prev = 0
for i in 0..<arr.count {
if i > 0 && arr[i] <= prev {
result = i
break
}
prev = arr[i]
}
return result
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
var i = 0
while i < arr.count - 1 {
if arr[i] < arr[i + 1] {
result = i
break
}
i += 1
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var i = 0
while i < arr.count - 1 {
if arr[i] < arr[i + 1] {
result = i
break
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
var last = 0
for i in 0..<arr.count {
if arr[i] > last {
result = i
last = arr[i]
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var last = 0
for i in 0..<arr.count {
if arr[i] > last {
result = i
last = arr[i]
}
}
return result
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<arr.count {
if arr[i] <= max {
max = arr[i]
}
}
return max
}
```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 max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<arr.count {
if arr[i] <= max {
max = arr[i]
}
}
return max
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var prev = 0
var index = 0
for i in 1..<arr.count {
if arr[i] > prev {
prev = arr[i]
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 {
var prev = 0
var index = 0
for i in 1..<arr.count {
if arr[i] > prev {
prev = arr[i]
index = i
}
}
return index
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var max = -1
for (index, value) in arr.enumerated() {
if index > 0 {
if value > arr[index - 1] {
max = index
}
}
}
return max
}
```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 max = -1
for (index, value) in arr.enumerated() {
if index > 0 {
if value > arr[index - 1] {
max = index
}
}
}
return max
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
result = i
max = arr[i]
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
result = i
max = arr[i]
}
}
return result
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
var last = Int.min
for (index, value) in arr.enumerated() {
if value > last {
maxIndex = index
}
last = value
}
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
var last = Int.min
for (index, value) in arr.enumerated() {
if value > last {
maxIndex = index
}
last = value
}
return maxIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
var prev = 0
for i in 0..<arr.count {
if arr[i] > prev {
result = i
prev = arr[i]
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var prev = 0
for i in 0..<arr.count {
if arr[i] > prev {
result = i
prev = arr[i]
}
}
return result
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
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?
var smallest: Int?
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 largest = 0
var smallest = 0
var largestNegative = 0
var smallestPositive = 0
var negative = false
var positive = false
for i in lst {
if i < 0 {
negative = true
if i > largestNegative {
largestNegative = i
}
} else {
positive = true
if i < smallestPositive {
smallestPositive = i
}
}
}
if negative {
largest = largestNegative
}
if positive {
smallest = smallestPositive
}
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 = 0
var smallest = 0
var largestNegative = 0
var smallestPositive = 0
var negative = false
var positive = false
for i in lst {
if i < 0 {
negative = true
if i > largestNegative {
largestNegative = i
}
} else {
positive = true
if i < smallestPositive {
smallestPositive = i
}
}
}
if negative {
largest = largestNegative
}
if positive {
smallest = smallestPositive
}
return (largest, smallest)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largestNegative = Int.min
var smallestPositive = Int.max
for i in lst {
if i < 0 {
largestNegative = max(largestNegative, i)
} else if i > 0 {
smallestPositive = min(smallestPositive, i)
}
}
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.min
var smallestPositive = Int.max
for i in lst {
if i < 0 {
largestNegative = max(largestNegative, i)
} else if i > 0 {
smallestPositive = min(smallestPositive, i)
}
}
return (largestNegative, smallestPositive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negatives = lst.filter { $0 < 0 }
let positives = lst.filter { $0 > 0 }
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?) {
let negatives = lst.filter { $0 < 0 }
let positives = lst.filter { $0 > 0 }
return (negatives.max(), positives.min())
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negatives = lst.filter { $0 < 0 }
let positives = lst.filter { $0 > 0 }
let smallest = negatives.min()
let largest = positives.max()
return (smallest, largest)
}
```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 negatives = lst.filter { $0 < 0 }
let positives = lst.filter { $0 > 0 }
let smallest = negatives.min()
let largest = positives.max()
return (smallest, largest)
}
```
// XCTAssertTrue failed
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?) {
var largest = 0
var smallest = 0
var largestNegative = 0
var smallestPositive = 0
for i in lst {
if i > 0 {
if i > largest {
largest = i
}
} else if i < 0 {
if i < smallest {
smallest = i
}
}
}
if largest > 0 {
largestNegative = largest
}
if smallest < 0 {
smallestPositive = smallest
}
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 largest = 0
var smallest = 0
var largestNegative = 0
var smallestPositive = 0
for i in lst {
if i > 0 {
if i > largest {
largest = i
}
} else if i < 0 {
if i < smallest {
smallest = i
}
}
}
if largest > 0 {
largestNegative = largest
}
if smallest < 0 {
smallestPositive = smallest
}
return (largestNegative, smallestPositive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
return (lst.max(), lst.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?) {
return (lst.max(), lst.min())
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest = 0
var smallest = 0
var largestNegative = 0
var smallestPositive = 0
for i in lst {
if i < 0 {
if i > largestNegative {
largestNegative = i
}
} else if i > 0 {
if i < smallestPositive {
smallestPositive = i
}
}
}
if largestNegative > 0 {
largest = largestNegative
} else if smallestPositive < 0 {
smallest = smallestPositive
}
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 = 0
var smallest = 0
var largestNegative = 0
var smallestPositive = 0
for i in lst {
if i < 0 {
if i > largestNegative {
largestNegative = i
}
} else if i > 0 {
if i < smallestPositive {
smallestPositive = i
}
}
}
if largestNegative > 0 {
largest = largestNegative
} else if smallestPositive < 0 {
smallest = smallestPositive
}
return (largest, smallest)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for i in lst {
if i > 0 {
if smallest == nil || i < smallest! {
smallest = i
}
} else if i < 0 {
if largest == nil || i > largest! {
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 largest: Int? = nil
var smallest: Int? = nil
for i in lst {
if i > 0 {
if smallest == nil || i < smallest! {
smallest = i
}
} else if i < 0 {
if largest == nil || i > largest! {
largest = i
}
}
}
return (largest, smallest)
}
```
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.doubleValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.doubleValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareFive(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFive(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFive(a:.stringValue
return a > b? a : b // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // cannot convert value of type 'Double?' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot convert value of type 'Int' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // expected expression
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot convert value of type 'Double' to expected argument type 'TaskPriority'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // cannot convert value of type 'Int?' to expected argument type 'TaskPriority'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot convert value of type 'Int' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot convert value of type 'Double?' to expected argument type 'TaskPriority'
return a > b? a : b // expected expression
return a > b? a : b // cannot convert value of type 'Int?' to expected argument type 'TaskPriority'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert value of type 'Double' to expected argument type 'TaskPriority'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert value of type 'Int' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // cannot convert value of type 'Double?' to expected argument type 'TaskPriority'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // cannot convert value of type 'Int?' to expected argument type 'TaskPriority'
return a > b? a : b // cannot convert value of type 'Double' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // expression of type 'String' is unused
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),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) :.intValue(b)
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) :.doubleValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.intValue(let b)):
return a > b?.intValue(a) :.intValue(b)
case (.doubleValue(let a),.doubleValue(let b)):
return a > b?.doubleValue(a) :.doubleValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
```
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.stringValue(a) :.doubleValue(b) // value of type 'Double' has no member 'stringValue'
return a > b?.stringValue(a) :.doubleValue(b) // expected expression
return a > b?.stringValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.doubleValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.stringValue(b) // value of type 'String' has no member 'doubleValue'
return a > b?.doubleValue(a) :.stringValue(b) // expected expression
return a > b?.doubleValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.intValue(a) :.stringValue(b) // expected expression
return a > b?.intValue(a) :.stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.stringValue(b) // value of type 'String' has no member 'intValue'
return a > b?.intValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.stringValue(a) :.intValue(b) // value of type 'Int' has no member 'stringValue'
return a > b?.stringValue(a) :.intValue(b) // expected expression
return a > b?.stringValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.intValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.intValue(b) // expected expression
return a > b?.intValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.intValue(b) // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) :.intValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.doubleValue(b) // expected expression
return a > b?.doubleValue(a) :.doubleValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) :.doubleValue(b) // value of type 'Double' has no member 'doubleValue'
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.doubleValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.stringValue(b)):
return a > b? a : b
case let (.stringValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.stringValue(b)):
return a > b? a : b
case let (.stringValue(a),.doubleValue(b)):
return a > b? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.doubleValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b? a : b
case let (.doubleValue(a),.intValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.stringValue(b)):
return a > b? a : b
case let (.stringValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.stringValue(b)):
return a > b? a : b
case let (.stringValue(a),.doubleValue(b)):
return a > b? a : b
default:
return nil
}
}
```
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // expected expression
return a > b? a : b // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // cannot convert value of type 'Int' to expected argument type 'TaskPriority'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // cannot convert value of type 'Double?' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot convert value of type 'Int?' to expected argument type 'TaskPriority'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert value of type 'Double' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // expected expression
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot convert value of type 'Int' to expected argument type 'TaskPriority'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot convert value of type 'String?' to expected argument type 'TaskPriority'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // cannot convert value of type 'Int?' to expected argument type 'TaskPriority'
return a > b? a : b // cannot convert value of type 'String' to expected argument type 'TaskPriority'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert value of type 'String?' to expected argument type 'TaskPriority'
return a > b? a : b // expected expression
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot convert value of type 'Double' to expected argument type 'TaskPriority'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // expected expression
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // cannot convert value of type 'String' to expected argument type 'TaskPriority'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert value of type 'Double?' to expected argument type 'TaskPriority'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.doubleValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) :.doubleValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
case let (.stringValue(a),.doubleValue(b)):
return a > "\(b)"?.stringValue(a) :.doubleValue(b)
case let (.doubleValue(a),.stringValue(b)):
return a > "\(b)"?.doubleValue(a) :.stringValue(b)
case let (.intValue(a),.stringValue(b)):
return a > "\(b)"?.intValue(a) :.stringValue(b)
case let (.stringValue(a),.intValue(b)):
return a > "\(b)"?.stringValue(a) :.intValue(b)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.doubleValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) :.doubleValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
case let (.stringValue(a),.doubleValue(b)):
return a > "\(b)"?.stringValue(a) :.doubleValue(b)
case let (.doubleValue(a),.stringValue(b)):
return a > "\(b)"?.doubleValue(a) :.stringValue(b)
case let (.intValue(a),.stringValue(b)):
return a > "\(b)"?.intValue(a) :.stringValue(b)
case let (.stringValue(a),.intValue(b)):
return a > "\(b)"?.stringValue(a) :.intValue(b)
default:
return nil
}
}
```
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) :.doubleValue(b) // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.doubleValue(b) // expected expression
return a > b?.doubleValue(a) :.doubleValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // value of type 'String' has no member 'stringValue'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // expected expression
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // expected expression
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // value of type 'String' has no member 'doubleValue'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.intValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.intValue(a) :.stringValue(b) // expected expression
return a > "\(b)"?.intValue(a) :.stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > "\(b)"?.intValue(a) :.stringValue(b) // value of type 'String' has no member 'intValue'
return a > "\(b)"?.intValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.intValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > "\(b)"?.stringValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.stringValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.stringValue(a) :.intValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > "\(b)"?.stringValue(a) :.intValue(b) // value of type 'String' has no member 'stringValue'
return a > "\(b)"?.stringValue(a) :.intValue(b) // expected expression
return a > "\(b)"?.stringValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' 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 let (.intValue(a),.intValue(b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case let (.doubleValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b?.intValue(a) : b > a?.intValue(b) : nil
case let (.doubleValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareTwo(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareThree(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareThree(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareThree(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.doubleValue(2.5)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("6")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil
case let (.stringValue(a),
return a > b?.intValue(a) : b > a?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of type 'Int' has no member 'intValue'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.intValue(a) : b > a?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : b > a?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // expected expression
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // expected expression
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // expected expression
return a > b?.intValue(a) : b > a?.doubleValue(b) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // expected expression
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) : b > a?.intValue(b) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // expected expression
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) : b > a?.stringValue(b) : nil // value of optional type 'String?' must be unwrapped to a value of type 'String'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a < b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a < b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a < b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a < b?.doubleValue(a) :.intValue(a)
case let (.doubleValue(a),.intValue(b)):
return a < b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a < b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the smaller 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)) ==.intValue(1)
// compareTwo(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareTwo(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("5,1")
// compareTwo(a:.stringValue("1"), b:.intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a < b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a < b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a < b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// 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("5,1")
// compareThree(a:.stringValue("1"), b:.intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.doubleValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the smaller variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// compareFour(a:.intValue(1), b:.doubleValue(2.5)) ==.intValue(1)
// compareFour(a:.intValue(1), b:.stringValue("2,3")) ==.stringValue("2,3")
// compareFour(a:.stringValue("5,1"), b:.stringValue("6")) ==.stringValue("5,1")
// compareFour(a:.stringValue("1"), b:.intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a < b?.doubleValue(a) :.intValue(a)
case let (.doubleValue(a),.intValue(b)):
return a < b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a < b?.stringValue(a) :.stringValue(b)
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a < b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a < b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a < b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a < b?.intValue(a) :.doubleValue(b) // expected expression
return a < b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a < b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a < b?.doubleValue(a) :.intValue(b) // expected expression
return a < b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a < b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a < b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a < b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a < b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a < b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a < b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a < b?.stringValue(a) :.stringValue(b) // expected expression
return a < b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a < b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a < b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.doubleValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.doubleValue(a) :.doubleValue(b) // expected expression
return a > b?.doubleValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.doubleValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.doubleValue(b) // value of type 'Double' has no member 'doubleValue'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a < b?.doubleValue(a) :.intValue(a) // consecutive statements on a line must be separated by ';'
return a < b?.doubleValue(a) :.intValue(a) // cannot use optional chaining on non-optional value of type 'Double'
return a < b?.doubleValue(a) :.intValue(a) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a < b?.doubleValue(a) :.intValue(a) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a < b?.doubleValue(a) :.intValue(a) // expected expression
return a < b?.doubleValue(a) :.intValue(a) // value of type 'Double' has no member 'doubleValue'
return a < b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a < b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a < b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a < b?.doubleValue(a) :.intValue(b) // expected expression
return a < b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a < b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a < b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a < b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a < b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a < b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a < b?.stringValue(a) :.stringValue(b) // expected expression
return a < b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.doubleValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.intValue(b)):
return a > b? a : b
case let (.doubleValue(a),.doubleValue(b)):
return a > b? a : b
case let (.stringValue(a),.stringValue(b)):
return a > b? a : b
default:
return nil
}
}
```
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Int' is unused
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Int'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'Double' is unused
return a > b? a : b // expected expression
return a > b? a : b // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'Double'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // expression of type 'String' is unused
return a > b? a : b // expected expression
return a > b? a : b // consecutive statements on a line must be separated by ';'
return a > b? a : b // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b? a : b // cannot use optional chaining on non-optional value of type 'String'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
case let (.stringValue(a),.doubleValue(b)):
return a > "\(b)"?.stringValue(a) :.doubleValue(b)
case let (.doubleValue(a),.stringValue(b)):
return a > "\(b)"?.doubleValue(a) :.stringValue(b)
case let (.intValue(a),.stringValue(b)):
return a > "\(b)"?.intValue(a) :.stringValue(b)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case let (.intValue(a),.doubleValue(b)):
return a > b?.intValue(a) :.doubleValue(b)
case let (.doubleValue(a),.intValue(b)):
return a > b?.doubleValue(a) :.intValue(b)
case let (.stringValue(a),.stringValue(b)):
return a > b?.stringValue(a) :.stringValue(b)
case let (.stringValue(a),.doubleValue(b)):
return a > "\(b)"?.stringValue(a) :.doubleValue(b)
case let (.doubleValue(a),.stringValue(b)):
return a > "\(b)"?.doubleValue(a) :.stringValue(b)
case let (.intValue(a),.stringValue(b)):
return a > "\(b)"?.intValue(a) :.stringValue(b)
default:
return nil
}
}
```
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // value of type 'String' has no member 'stringValue'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // expected expression
return a > "\(b)"?.stringValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // expected expression
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.doubleValue(a) :.stringValue(b) // value of type 'String' has no member 'doubleValue'
return a > "\(b)"?.intValue(a) :.stringValue(b) // expected expression
return a > "\(b)"?.intValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > "\(b)"?.intValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > "\(b)"?.intValue(a) :.stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > "\(b)"?.intValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > "\(b)"?.intValue(a) :.stringValue(b) // value of type 'String' has no member 'intValue'
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),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// 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),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be. or,
// 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),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.stringValue(a) :.doubleValue(b) // value of type 'Double' has no member 'stringValue'
return a > b?.stringValue(a) :.doubleValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.doubleValue(b) // expected expression
return a > b?.stringValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.stringValue(b) // value of type 'String' has no member 'doubleValue'
return a > b?.doubleValue(a) :.stringValue(b) // expected expression
return a > b?.doubleValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.doubleValue(a) :.stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.stringValue(b) // value of type 'String' has no member 'intValue'
return a > b?.intValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.intValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.stringValue(a) :.intValue(b) // expected expression
return a > b?.stringValue(a) :.intValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.intValue(b) // value of type 'Int' has no member 'stringValue'
return a > b?.stringValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
case (.intValue(let a),.doubleValue(let b)): // case is already handled by previous patterns; consider removing it
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
case (.doubleValue(let a),.intValue(let b)): // case is already handled by previous patterns; consider removing it
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.stringValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.stringValue(a) :.stringValue(b) // value of type 'String' has no member 'stringValue'
return a > b?.stringValue(a) :.stringValue(b) // expected expression
return a > b?.stringValue(a) :.stringValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.stringValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.stringValue(a) :.doubleValue(b) // expected expression
return a > b?.stringValue(a) :.doubleValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.doubleValue(b) // value of type 'Double' has no member 'stringValue'
return a > b?.doubleValue(a) :.stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.doubleValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.doubleValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.stringValue(b) // expected expression
return a > b?.doubleValue(a) :.stringValue(b) // value of type 'String' has no member 'doubleValue'
return a > b?.intValue(a) :.stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.stringValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.stringValue(b) // cannot use optional chaining on non-optional value of type 'String'
return a > b?.intValue(a) :.stringValue(b) // expected expression
return a > b?.intValue(a) :.stringValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.intValue(a) :.stringValue(b) // value of type 'String' has no member 'intValue'
return a > b?.stringValue(a) :.intValue(b) // expected expression
return a > b?.stringValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.stringValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.stringValue(a) :.intValue(b) // value of optional type 'String?' must be unwrapped to a value of type 'String'
return a > b?.stringValue(a) :.intValue(b) // value of type 'Int' has no member 'stringValue'
return a > b?.stringValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
case (.intValue(let a),.doubleValue(let b)): // case is already handled by previous patterns; consider removing it
return a > b?.intValue(a) :.doubleValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b?.intValue(a) :.doubleValue(b) // consecutive statements on a line must be separated by ';'
return a > b?.intValue(a) :.doubleValue(b) // cannot use optional chaining on non-optional value of type 'Double'
return a > b?.intValue(a) :.doubleValue(b) // expected expression
return a > b?.intValue(a) :.doubleValue(b) // value of type 'Double' has no member 'intValue'
return a > b?.intValue(a) :.doubleValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
case (.doubleValue(let a),.intValue(let b)): // case is already handled by previous patterns; consider removing it
return a > b?.doubleValue(a) :.intValue(b) // expected expression
return a > b?.doubleValue(a) :.intValue(b) // cannot use optional chaining on non-optional value of type 'Int'
return a > b?.doubleValue(a) :.intValue(b) // value of type 'Int' has no member 'doubleValue'
return a > b?.doubleValue(a) :.intValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > b?.doubleValue(a) :.intValue(b) // cannot convert return expression of type 'Bool' to return type 'Value?'
return a > b?.doubleValue(a) :.intValue(b) // consecutive statements on a line must be separated by ';'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
```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),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.stringValue(let b)):
return a > b?.stringValue(a) :.stringValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a) :.intValue(b)
case (.stringValue(let a),.doubleValue(let b)):
return a > b?.stringValue(a) :.doubleValue(b)
case (.doubleValue(let a),.stringValue(let b)):
return a > b?.doubleValue(a) :.stringValue(b)
case (.intValue(let a),.stringValue(let b)):
return a > b?.intValue(a) :.stringValue(b)
case (.stringValue(let a),.intValue(let b)):
return a > b?.stringValue(a) :.intValue(b)
case (.intValue(let a),.doubleValue(let b)):
return a > b?.intValue(a) :.doubleValue(b)
case (.doubleValue(let a),.intValue(let b)):
return a > b?.doubleValue(a
XCTAssertTrue(compareOne(a: .intValue(1), b: .intValue(2)) == .intValue(2)) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .intValue(1), b: .intValue(2)) == .intValue(2)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(1), b: .intValue(2)) == .intValue(2)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)) // cannot infer contextual base in reference to member 'doubleValue'
XCTAssertTrue(compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .intValue(2), b: .intValue(3)) == .intValue(3)) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .intValue(2), b: .intValue(3)) == .intValue(3)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(2), b: .intValue(3)) == .intValue(3)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(5), b: .intValue(6)) == .intValue(6)) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .intValue(5), b: .intValue(6)) == .intValue(6)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(5), b: .intValue(6)) == .intValue(6)) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")) // cannot infer contextual base in reference to member 'stringValue'
XCTAssertTrue(compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")) // cannot infer contextual base in reference to member 'stringValue'
XCTAssertTrue(compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")) // cannot infer contextual base in reference to member 'stringValue'
XCTAssertTrue(compareOne(a: .stringValue("1"), b: .stringValue("2")) == .stringValue("2")) // cannot infer contextual base in reference to member 'stringValue'
XCTAssertTrue(compareOne(a: .stringValue("1"), b: .stringValue("2")) == .stringValue("2")) // cannot find 'compareOne' in scope
XCTAssertTrue(compareOne(a: .stringValue("1"), b: .stringValue("2")) == .stringValue("2")) // cannot infer contextual base in reference to member 'stringValue'
XCTAssertTrue(compareOne(a: .stringValue("1"), b: .intValue(1)) == nil) // cannot infer contextual base in reference to member 'intValue'
XCTAssertTrue(compareOne(a: .stringValue("1"), b: .intValue(1)) == nil) // cannot infer contextual base in reference to member 'stringValue'
XCTAssertTrue(compareOne(a: .stringValue("1"), b: .intValue(1)) == nil) // cannot find 'compareOne' in scope
```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 {
// 1. 1 + 1 + 1 + 1 = 4
// 2. 2 + 2 + 2 = 6
// 3. 4 + 4 = 8
// 4. 2 + 2 + 2 + 2 = 8
// 5. 4 + 4 + 2 = 10
// 6. 2 + 2 + 2 + 2 + 2 = 10
// 7. 4 + 4 + 4 = 12
// 8. 2 + 2 + 2 + 2 + 2 + 2 = 12
// 9. 4 + 4 + 4 + 2 = 14
// 10. 2 + 2 + 2 + 2 + 2 + 2 + 2 = 14
// 11. 4 + 4 + 4 + 4 = 16
// 12. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 16
// 13. 4 + 4 + 4 + 4 + 2 = 18
// 14. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 18
// 15. 4 + 4 + 4 + 4 + 4 = 20
// 16. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 20
// 17. 4 + 4 + 4 + 4 + 4 + 2 = 22
// 18. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 22
// 19. 4 + 4 + 4 + 4 + 4 + 4 = 24
// 20. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 24
// 21. 4 + 4 + 4 + 4 + 4 + 4 + 2 = 26
// 22. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 26
// 23. 4 + 4 + 4 + 4 + 4 + 4 + 4 = 28
// 24. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 28
// 25. 4 + 4 + 4 + 4 + 4 + 4 + 4 + 2 = 30
// 26. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 30
// 27. 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 = 32
// 28. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 32
// 29. 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 2 = 34
// 30. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 = 34
// 31. 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 = 36
// 32. 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2
XCTAssertTrue(isEqualToSumEven(n: 4) == false) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 6) == false) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 8) == true) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 10) == true) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 11) == false) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 12) == true) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 13) == false) // cannot find 'isEqualToSumEven' in scope
XCTAssertTrue(isEqualToSumEven(n: 16) == true) // cannot find 'isEqualToSumEven' in scope
func isEqualToSumEven(n: Int) -> Bool {
return n % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 4 == 0
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
return n % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 4 == 0
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
for a in 0...n/4 {
for b in a+1...n/4 {
for c in b+1...n/4 {
for d in c+1...n/4 {
if a + b + c + d == 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 {
for a in 0...n/4 {
for b in a+1...n/4 {
for c in b+1...n/4 {
for d in c+1...n/4 {
if a + b + c + d == n {
return true
}
}
}
}
}
return false
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isEqualToSumEven(n: Int) -> Bool {
return (n - 2) % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return (n - 2) % 4 == 0
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...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 2...n {
if i % 2 == 0 {
sum += i
if sum == n {
return true
}
}
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while i < n {
sum += i
i += 2
}
return sum == n
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while i < n {
sum += i
i += 2
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
return n % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 4 == 0
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
return 1
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
return 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 {
return 0
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
return 0
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
// Write your code here
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 {
// Write your code here
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
return 0
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
return 0
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
return 0
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
return 0
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_", options:.literal, range: nil)
.replacingOccurrences(of: " ", with: "-", options:.literal, range: nil)
}
```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 {
return text.replacingOccurrences(of: " ", with: "_", options:.literal, range: nil)
.replacingOccurrences(of: " ", with: "-", options:.literal, range: nil)
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
return text.replacingOccurrences(of: " ", with: "_").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 {
return text.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: " ", with: "-")
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No"
}
```
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // expected expression
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert return expression of type '()' to return type 'String'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' requires a contextual type
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // string literal is unused
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "[0-9]{4}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
func fileNameCheck(fileName: String) -> String {
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z].*[.][txt|exe|dll]$", options: [])
let range = NSRange(fileName.startIndex..., in: fileName)
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "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 regex = try! NSRegularExpression(pattern: "^[a-zA-Z].*[.][txt|exe|dll]$", options: [])
let range = NSRange(fileName.startIndex..., in: fileName)
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No"
}
```
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // cannot assign value of type 'Optional<_>' to type 'NSTextCheckingResult'
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // cannot convert return expression of type '()' to return type 'String'
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // string literal is unused
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // cannot assign through '!': function call returns immutable value
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // 'nil' requires a contextual type
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // expected expression
return regex.firstMatch(in: fileName, options: [], range: range)!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No"
}
```
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // string literal is unused
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // expected expression
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert return expression of type '()' to return type 'String'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' requires a contextual type
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No"
}
```
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // expected expression
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // 'nil' requires a contextual type
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // string literal is unused
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // cannot convert return expression of type '()' to return type 'String'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "\\d{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.txt|\\.exe|\\.dll")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No"
}
```
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // string literal is unused
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // expected expression
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // cannot convert return expression of type '()' to return type 'String'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' requires a contextual type
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // 'nil' is not compatible with expected argument type 'Bool'
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
return fileName.range(of: "[0-9]{1,3}") == nil && fileName.range(of: "\\.")!= nil && fileName.range(of: "^[a-zA-Z]")!= nil && fileName.range(of: "\\.(txt|exe|dll)$")!= nil? "Yes" : "No" // '=' must have consistent whitespace on both sides
```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 validCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
let validExtensions = ["txt", "exe", "dll"]
let validCharactersInFileName = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let validCharactersInExtension = fileName.rangeOfCharacter(from: validCharacters.inverted) == nil
let valid
XCTAssertTrue(fileNameCheck(fileName: "example.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1example.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s1sdf3.asd") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "K.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "MY16FILE3.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "His12FILE94.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "_Y.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "?aREYA.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "/thisIsValid.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.wow") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txtexe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "#this2I4s5valid.ten") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "@this1Is6Valid.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIs12valid.6exe4.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "all.exe.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_No.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "Is3youfault.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "noOne#knows.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1I563_Yes3.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_Yes3.txtt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final..txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final132") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "F4indsartal132.") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: ".txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s.") == "No") // cannot find 'fileNameCheck' in scope
func fileNameCheck(fileName: String) -> String {
let valid = fileName.range(of: "[a-zA-Z]+\\.[txt|exe|dll]")!= nil
return valid? "Yes" : "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 valid = fileName.range(of: "[a-zA-Z]+\\.[txt|exe|dll]")!= nil
return valid? "Yes" : "No"
}
```
let valid = fileName.range(of: "[a-zA-Z]+\\.[txt|exe|dll]")!= nil // '=' must have consistent whitespace on both sides
let valid = fileName.range(of: "[a-zA-Z]+\\.[txt|exe|dll]")!= nil // cannot assign through '!': function call returns immutable value
let valid = fileName.range(of: "[a-zA-Z]+\\.[txt|exe|dll]")!= nil // 'nil' cannot be assigned to type 'Range<String.Index>'
return valid? "Yes" : "No" // expected expression
return valid? "Yes" : "No" // cannot convert return expression of type 'Optional<_>' to return type 'String'
return valid? "Yes" : "No" // consecutive statements on a line must be separated by ';'
return valid? "Yes" : "No" // string literal is unused
return valid? "Yes" : "No" // consecutive statements on a line must be separated by ';'
func fileNameCheck(fileName: String) -> String {
let validCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "."))
let validExtensions = ["txt", "exe", "dll"]
let validCharactersSet = CharacterSet(charactersIn: fileName)
let validCharactersCount = validCharactersSet.intersection(validCharacters).count
let validExtensionsSet = CharacterSet(charactersIn: fileName)
let validExtensionsCount = validExtensionsSet.intersection(validCharacters).count
let validCharactersCountIsThree = validCharactersCount <= 3
let validCharactersCountIsThreeAndValidCharactersSet = validCharactersSet.isSubset(of: validCharacters)
let validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSet = validCharactersSet.isSubset(of: validCharacters) && validExtensionsSet.isSubset(of: validCharacters)
let validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCount = validExtensionsCount == 1
let validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCountAndValidExtensions = validExtensions[0] == validExtensions[0]
return validCharactersCountIsThree && validCharactersCountIsThreeAndValidCharactersSet && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSet && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCount && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCountAndValidExtensions
}
```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 validCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "."))
let validExtensions = ["txt", "exe", "dll"]
let validCharactersSet = CharacterSet(charactersIn: fileName)
let validCharactersCount = validCharactersSet.intersection(validCharacters).count
let validExtensionsSet = CharacterSet(charactersIn: fileName)
let validExtensionsCount = validExtensionsSet.intersection(validCharacters).count
let validCharactersCountIsThree = validCharactersCount <= 3
let validCharactersCountIsThreeAndValidCharactersSet = validCharactersSet.isSubset(of: validCharacters)
let validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSet = validCharactersSet.isSubset(of: validCharacters) && validExtensionsSet.isSubset(of: validCharacters)
let validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCount = validExtensionsCount == 1
let validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCountAndValidExtensions = validExtensions[0] == validExtensions[0]
return validCharactersCountIsThree && validCharactersCountIsThreeAndValidCharactersSet && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSet && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCount && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCountAndValidExtensions
}
```
let validCharactersCount = validCharactersSet.intersection(validCharacters).count // value of type 'CharacterSet' has no member 'count'
let validExtensionsCount = validExtensionsSet.intersection(validCharacters).count // value of type 'CharacterSet' has no member 'count'
return validCharactersCountIsThree && validCharactersCountIsThreeAndValidCharactersSet && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSet && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCount && validCharactersCountIsThreeAndValidCharactersSetAndValidExtensionsSetAndValidExtensionsCountAndValidExtensions // cannot convert return expression of type 'Bool' to return type 'String'
func fileNameCheck(fileName: String) -> String {
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
return "Yes"
}
```
// XCTAssertTrue failed
```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 fileNameArr = fileName.components(separatedBy: ".")
let fileNameArrCount = fileNameArr.count
let fileNameArrLast = fileNameArr[fileNameArrCount - 1]
let fileNameArrFirst = fileNameArr[0]
let fileNameArrFirstFirst = fileNameArrFirst.first
let fileNameArrFirstFirstString = String(describing: fileNameArrFirstFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLast.first)
let fileNameArrLastFirst = fileNameArrLast.first
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing: fileNameArrLastFirst)
let fileNameArrLastFirstString = String(describing
XCTAssertTrue(fileNameCheck(fileName: "example.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1example.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s1sdf3.asd") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "K.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "MY16FILE3.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "His12FILE94.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "_Y.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "?aREYA.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "/thisIsValid.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.wow") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txtexe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "#this2I4s5valid.ten") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "@this1Is6Valid.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIs12valid.6exe4.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "all.exe.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_No.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "Is3youfault.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "noOne#knows.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1I563_Yes3.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_Yes3.txtt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final..txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final132") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "F4indsartal132.") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: ".txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s.") == "No") // cannot find 'fileNameCheck' in scope
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
for i in 2..<n {
if n % i == 0 { return false }
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
for i in 2..<n {
if n % i == 0 { return false }
}
return true
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
var words = sentence.components(separatedBy: " ")
var result = [String]()
for word in words {
if isPrime(word.count) {
result.append(word)
}
}
return result.joined(separator: " ")
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if n == 2 { return true }
if n % 2 == 0 { return false }
for i in 3...Int(sqrt(Double(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 {
var words = sentence.components(separatedBy: " ")
var result = [String]()
for word in words {
if isPrime(word.count) {
result.append(word)
}
}
return result.joined(separator: " ")
}
func isPrime(_ n: Int) -> Bool {
if n < 2 { return false }
if n == 2 { return true }
if n % 2 == 0 { return false }
for i in 3...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
var words = sentence.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// Fatal error: Range requires lowerBound <= upperBound
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
var words = sentence.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
var words = sentence.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
return sentence.split(separator: " ").filter { $0.count % 2 == 1 }.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 {
return sentence.split(separator: " ").filter { $0.count % 2 == 1 }.joined(separator: " ")
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
return sentence.components(separatedBy: " ").filter { $0.count % 2 == 1 }.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 {
return sentence.components(separatedBy: " ").filter { $0.count % 2 == 1 }.joined(separator: " ")
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
return sentence.components(separatedBy: " ").filter { $0.count % 2 == 1 }.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 {
return sentence.components(separatedBy: " ").filter { $0.count % 2 == 1 }.joined(separator: " ")
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ num: Int) -> Bool {
guard num > 1 else { 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 {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result
}
func isPrime(_ num: Int) -> Bool {
guard num > 1 else { return false }
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
let words = sentence.components(separatedBy: " ")
for word in words {
if isPrime(word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in:.whitespaces)
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func simplify(x: String, n: String) -> Bool {
let xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplifiedNumerator = xNumerator * nDenominator
let xSimplifiedDenominator = xDenominator * nNumerator
return xSimplifiedNumerator % xSimplifiedDenominator == 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 xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplifiedNumerator = xNumerator * nDenominator
let xSimplifiedDenominator = xDenominator * nNumerator
return xSimplifiedNumerator % xSimplifiedDenominator == 0
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.components(separatedBy: "/").map { Int($0)! }
let n = n.components(separatedBy: "/").map { Int($0)! }
let gcd = gcd(x[0], n[0])
return x[0] / gcd == x[1] / gcd && n[0] / gcd == n[1] / gcd
}
func gcd(_ 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
// 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: "/").map { Int($0)! }
let n = n.components(separatedBy: "/").map { Int($0)! }
let gcd = gcd(x[0], n[0])
return x[0] / gcd == x[1] / gcd && n[0] / gcd == n[1] / gcd
}
func gcd(_ a: Int, _ b: Int) -> Int {
var a = a
var b = b
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // '=' must have consistent whitespace on both sides
func simplify(x: String, n: String) -> Bool {
let xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplified = xNumerator * nDenominator
let nSimplified = nNumerator * xDenominator
return xSimplified % nSimplified == 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 xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplified = xNumerator * nDenominator
let nSimplified = nNumerator * xDenominator
return xSimplified % nSimplified == 0
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
return xNumerator * nDenominator == xDenominator * nNumerator
}
```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 xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
return xNumerator * nDenominator == xDenominator * nNumerator
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xArr = x.components(separatedBy: "/")
let nArr = n.components(separatedBy: "/")
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let x = xNum * nDen
let n = nNum * xDen
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 xArr = x.components(separatedBy: "/")
let nArr = n.components(separatedBy: "/")
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let x = xNum * nDen
let n = nNum * xDen
return x % n == 0
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
return true
}
```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 {
return true
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplifiedNumerator = xNumerator * nDenominator
let xSimplifiedDenominator = xDenominator * nNumerator
return xSimplifiedNumerator % xSimplifiedDenominator == 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 xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplifiedNumerator = xNumerator * nDenominator
let xSimplifiedDenominator = xDenominator * nNumerator
return xSimplifiedNumerator % xSimplifiedDenominator == 0
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xArr = x.components(separatedBy: "/")
let nArr = n.components(separatedBy: "/")
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let x = xNum / xDen
let n = nNum / nDen
let result = x * n
return result.isMultiple(of: 1)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.components(separatedBy: "/")
let nArr = n.components(separatedBy: "/")
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let x = xNum / xDen
let n = nNum / nDen
let result = x * n
return result.isMultiple(of: 1)
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplifiedNumerator = xNumerator * nDenominator
let xSimplifiedDenominator = xDenominator * nNumerator
return xSimplifiedNumerator % xSimplifiedDenominator == 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 xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let xSimplifiedNumerator = xNumerator * nDenominator
let xSimplifiedDenominator = xDenominator * nNumerator
return xSimplifiedNumerator % xSimplifiedDenominator == 0
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let x = xNumerator * nDenominator
let n = nNumerator * xDenominator
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 xComponents = x.components(separatedBy: "/")
let nComponents = n.components(separatedBy: "/")
let xNumerator = Int(xComponents[0])!
let xDenominator = Int(xComponents[1])!
let nNumerator = Int(nComponents[0])!
let nDenominator = Int(nComponents[1])!
let x = xNumerator * nDenominator
let n = nNumerator * xDenominator
return x % n == 0
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
return sum1 == sum2? $0 < $1 : 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 {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
```
let sum1 = $0.reduce(0, +) // value of type 'Int' has no member 'reduce'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // expected expression
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
if sum1 == sum2 {
return $0 < $1
}
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 {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
if sum1 == sum2 {
return $0 < $1
}
return sum1 < sum2
}
}
```
let sum1 = $0.reduce(0, +) // value of type 'Int' has no member 'reduce'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
if sum1!= sum2 {
return sum1 < sum2
}
return $0 < $1
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
if sum1!= sum2 {
return sum1 < sum2
}
return $0 < $1
}
}
```
let sum1 = $0.reduce(0, +) // value of type 'Int' has no member 'reduce'
if sum1!= sum2 { // '=' must have consistent whitespace on both sides
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let a = $0, b = $1
let sumA = a.reduce(0, +)
let sumB = b.reduce(0, +)
if sumA!= sumB {
return sumA < sumB
} else {
return a < b
}
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let a = $0, b = $1
let sumA = a.reduce(0, +)
let sumB = b.reduce(0, +)
if sumA!= sumB {
return sumA < sumB
} else {
return a < b
}
}
}
```
let sumA = a.reduce(0, +) // value of type 'Int' has no member 'reduce'
if sumA!= sumB { // '=' must have consistent whitespace on both sides
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
return sum1 == sum2? $0 < $1 : 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 {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
```
let sum1 = $0.reduce(0, +) // value of type 'Int' has no member 'reduce'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // expected expression
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0) { $0 + $1.digitSum }
let sum2 = $1.reduce(0) { $0 + $1.digitSum }
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
extension Int {
var digitSum: Int {
return String(self).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 {
let sum1 = $0.reduce(0) { $0 + $1.digitSum }
let sum2 = $1.reduce(0) { $0 + $1.digitSum }
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
extension Int {
var digitSum: Int {
return String(self).reduce(0) { $0 + Int(String($1))! }
}
}
```
let sum1 = $0.reduce(0) { $0 + $1.digitSum } // value of type 'Int' has no member 'reduce'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // expected expression
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
return sum1 == sum2? $0 < $1 : 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 {
let sum1 = $0.reduce(0, +)
let sum2 = $1.reduce(0, +)
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
```
let sum1 = $0.reduce(0, +) // value of type 'Int' has no member 'reduce'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // expected expression
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted { (a, b) -> Bool in
let sumA = a.reduce(0) { $0 + $1.digitSum }
let sumB = b.reduce(0) { $0 + $1.digitSum }
return sumA == sumB? a < b : sumA < sumB
}
}
extension Int {
var digitSum: Int {
return String(self).reduce(0) { $0 + $1.wholeNumberValue }
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted { (a, b) -> Bool in
let sumA = a.reduce(0) { $0 + $1.digitSum }
let sumB = b.reduce(0) { $0 + $1.digitSum }
return sumA == sumB? a < b : sumA < sumB
}
}
extension Int {
var digitSum: Int {
return String(self).reduce(0) { $0 + $1.wholeNumberValue }
}
}
```
let sumA = a.reduce(0) { $0 + $1.digitSum } // value of type 'Int' has no member 'reduce'
return sumA == sumB? a < b : sumA < sumB // expected expression
return sumA == sumB? a < b : sumA < sumB // consecutive statements on a line must be separated by ';'
return sumA == sumB? a < b : sumA < sumB // consecutive statements on a line must be separated by ';'
return String(self).reduce(0) { $0 + $1.wholeNumberValue } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0) { $0 + $1.digitSum }
let sum2 = $1.reduce(0) { $0 + $1.digitSum }
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
extension Int {
var digitSum: Int {
return String(self).reduce(0) { $0 + $1.wholeNumberValue }
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0) { $0 + $1.digitSum }
let sum2 = $1.reduce(0) { $0 + $1.digitSum }
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
extension Int {
var digitSum: Int {
return String(self).reduce(0) { $0 + $1.wholeNumberValue }
}
}
```
let sum1 = $0.reduce(0) { $0 + $1.digitSum } // value of type 'Int' has no member 'reduce'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // expected expression
return String(self).reduce(0) { $0 + $1.wholeNumberValue } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0) { $0 + $1.digitValue }
let sum2 = $1.reduce(0) { $0 + $1.digitValue }
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
extension Int {
var digitValue: Int {
return String(self).reduce(0) { $0 + $1.digitValue }
}
var digitCount: Int {
return String(self).count
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let sum1 = $0.reduce(0) { $0 + $1.digitValue }
let sum2 = $1.reduce(0) { $0 + $1.digitValue }
return sum1 == sum2? $0 < $1 : sum1 < sum2
}
}
extension Int {
var digitValue: Int {
return String(self).reduce(0) { $0 + $1.digitValue }
}
var digitCount: Int {
return String(self).count
}
}
```
let sum1 = $0.reduce(0) { $0 + $1.digitValue } // value of type 'Int' has no member 'reduce'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // consecutive statements on a line must be separated by ';'
return sum1 == sum2? $0 < $1 : sum1 < sum2 // expected expression
return String(self).reduce(0) { $0 + $1.digitValue } // missing argument label 'into:' in call
return String(self).reduce(0) { $0 + $1.digitValue } // no 'reduce' candidates produce the expected contextual result type 'Int'
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 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 % 10) % 2!= 0 && (num / 10) % 2!= 0 {
count += 1
}
}
return count
}
```
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 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) && (num % 10 % 2!= 0) {
count += 1
}
}
return count
}
```
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // expression is not assignable: binary operator returns immutable value
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // expression is not assignable: binary operator returns immutable value
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // expression is not assignable: binary operator returns immutable value
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10 % 2!= 0) { // cannot force unwrap value of non-optional type 'Int'
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 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 % 10) % 2!= 0 && (num / 10) % 2!= 0 {
count += 1
}
}
return count
}
```
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 % 2 == 1 && num / 10 % 2 == 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 % 2 == 1 && num / 10 % 2 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 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) % 2!= 0 {
count += 1
}
}
return count
}
```
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && num % 2!= 0 && (num % 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 % 2 == 1 && num / 10 % 2 == 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 % 2 == 1 && num / 10 % 2 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) {
count += 1
}
}
return count
}
```
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // expression is not assignable: binary operator returns immutable value
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // use of '=' in a boolean context, did you mean '=='?
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // expression is not assignable: binary operator returns immutable value
if num > 10 && (num % 2!= 0) && (num % 10!= 0) && (num % 10!= 1) { // expression is not assignable: binary operator returns immutable value
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 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 % 10) % 2!= 0 && (num / 10) % 2!= 0 {
count += 1
}
}
return count
}
```
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // '=' must have consistent whitespace on both sides
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if num > 10 && (num % 10) % 2!= 0 && (num / 10) % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
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 nums.filter {
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 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 % 2!= 0 && ($0 / 10) % 2!= 0
}.count
}
```
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // '=' must have consistent whitespace on both sides
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // cannot force unwrap value of non-optional type 'Int'
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // '=' must have consistent whitespace on both sides
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // cannot convert value of type '()' to closure result type 'Bool'
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // type 'Int' cannot be used as a boolean; test for '!= 0' instead
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // expression is not assignable: '&&' returns immutable value
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // expression is not assignable: '&&' returns immutable value
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // type 'Int' cannot be used as a boolean; test for '!= 0' instead
$0 > 10 && $0 % 2!= 0 && ($0 / 10) % 2!= 0 // cannot force unwrap value of non-optional type 'Int'
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<a.count {
for j in i+1..<a.count {
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 {
for j in i+1..<a.count {
for k in j+1..<a.count {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
var i = 1
while i < n {
var j = i + 1
while j < n {
var k = j + 1
while k < n {
if (i + j + k) % 3 == 0 {
count += 1
}
k += 1
}
j += 1
}
i += 1
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
var i = 1
while i < n {
var j = i + 1
while j < n {
var k = j + 1
while k < n {
if (i + j + k) % 3 == 0 {
count += 1
}
k += 1
}
j += 1
}
i += 1
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var result = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i + j + k) % 3 == 0 {
result += 1
}
}
}
}
return result
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var result = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i + j + k) % 3 == 0 {
result += 1
}
}
}
}
return result
}
getMaxTriples(n: 5)
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var count = 0
var i = 1
while i * i <= n {
var j = i + 1
while j * j <= n {
var k = j + 1
while k * k <= n {
if (i + j + k) % 3 == 0 {
count += 1
}
k += 1
}
j += 1
}
i += 1
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
var i = 1
while i * i <= n {
var j = i + 1
while j * j <= n {
var k = j + 1
while k * k <= n {
if (i + j + k) % 3 == 0 {
count += 1
}
k += 1
}
j += 1
}
i += 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 {
for j in i+1..<a.count {
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 {
for j in i+1..<a.count {
for k in j+1..<a.count {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i+j+k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if (i+j+k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if i + j + k % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i+1...n {
for k in j+1...n {
if i + j + k % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// Fatal error: Range requires lowerBound <= upperBound
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<a.count {
for j in i+1..<a.count {
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 {
for j in i+1..<a.count {
for k in j+1..<a.count {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
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 }
}
sortedListSum(lst: ["aa", "a", "aaa"])
sortedListSum(lst: ["ab", "a", "aaa", "cd"])
```
func sortedListSum(lst: [String]) -> [String] {
return lst.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.sorted { $0.count < $1.count }
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
return lst.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.sorted {
$0.count < $1.count || ($0.count == $1.count && $0 < $1)
}
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
return lst.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.sorted { $0.count < $1.count }
}
sortedListSum(lst: ["aa", "a", "aaa"])
sortedListSum(lst: ["ab", "a", "aaa", "cd"])
```
// XCTAssertTrue failed
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 }
}
sortedListSum(lst: ["aa", "a", "aaa"])
sortedListSum(lst: ["ab", "a", "aaa", "cd"])
```
func sortedListSum(lst: [String]) -> [String] {
return lst.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.sorted { $0.count < $1.count }
}
```
// XCTAssertTrue failed
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] {
return lst.sorted {
if $0.count == $1.count {
return $0 < $1
} else {
return $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.sorted {
if $0.count == $1.count {
return $0 < $1
} else {
return $0.count < $1.count
}
}
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
return lst.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] {
return lst.sorted(by: { $0.count < $1.count })
}
sortedListSum(lst: ["aa", "a", "aaa"])
sortedListSum(lst: ["ab", "a", "aaa", "cd"])
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
return lst.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.sorted { $0.count < $1.count }
}
sortedListSum(lst: ["aa", "a", "aaa"])
sortedListSum(lst: ["ab", "a", "aaa", "cd"])
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? 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 {
return n % 2 == 0? x : y
}
```
return n % 2 == 0? x : y // expression of type 'Int' is unused
return n % 2 == 0? x : y // expected expression
return n % 2 == 0? x : y // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? x : y // consecutive statements on a line must be separated by ';'
return n % 2 == 0? x : y // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? x : y // consecutive statements on a line must be separated by ';'
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0? y : 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 {
return n % 2 == 0? y : x
}
```
return n % 2 == 0? y : x // expected expression
return n % 2 == 0? y : x // expression of type 'Int' is unused
return n % 2 == 0? y : x // cannot convert return expression of type 'Bool' to return type 'Int'
return n % 2 == 0? y : x // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
return n % 2 == 0? y : x // consecutive statements on a line must be separated by ';'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num > 0 {
sum += Int(num * num)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num > 0 {
sum += Int(num * num)
}
}
return sum
}
```
if num.isInteger && num > 0 { // value of type 'Double' has no member 'isInteger'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num > 0 {
sum += Int(num * num)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num > 0 {
sum += Int(num * num)
}
}
return sum
}
```
if num.isInteger && num > 0 { // value of type 'Double' has no member 'isInteger'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num.isPositive {
if num.isOdd {
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.isInteger && num.isPositive {
if num.isOdd {
sum += Int(num * num)
}
}
}
return sum
}
```
if num.isInteger && num.isPositive { // value of type 'Double' has no member 'isInteger'
if num.isInteger && num.isPositive { // value of type 'Double' has no member 'isPositive'
if num.isOdd { // value of type 'Double' has no member 'isOdd'
func doubleTheDifference(lst: [Double]) -> Int {
return lst.reduce(0) { $0 + $1.isOdd? $1 * $1 : 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.reduce(0) { $0 + $1.isOdd? $1 * $1 : 0 }
}
```
return lst.reduce(0) { $0 + $1.isOdd? $1 * $1 : 0 } // consecutive statements on a line must be separated by ';'
return lst.reduce(0) { $0 + $1.isOdd? $1 * $1 : 0 } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return lst.reduce(0) { $0 + $1.isOdd? $1 * $1 : 0 } // consecutive statements on a line must be separated by ';'
return lst.reduce(0) { $0 + $1.isOdd? $1 * $1 : 0 } // value of type 'Double' has no member 'isOdd'
return lst.reduce(0) { $0 + $1.isOdd? $1 * $1 : 0 } // expected expression
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num.isPositive {
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.isInteger && num.isPositive {
sum += Int(num * num)
}
}
return sum
}
```
if num.isInteger && num.isPositive { // value of type 'Double' has no member 'isInteger'
if num.isInteger && num.isPositive { // value of type 'Double' has no member 'isPositive'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isInteger && num > 0 {
if num.isMultiple(of: 2) {
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.isInteger && num > 0 {
if num.isMultiple(of: 2) {
sum += Int(num * num)
}
}
}
return sum
}
```
if num.isInteger && num > 0 { // value of type 'Double' has no member 'isInteger'
if num.isMultiple(of: 2) { // value of type 'Double' has no member 'isMultiple'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num.isWholeNumber && num.isOdd {
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.isWholeNumber && num.isOdd {
sum += Int(num * num)
}
}
return sum
}
```
if num.isWholeNumber && num.isOdd { // value of type 'Double' has no member 'isOdd'
if num.isWholeNumber && num.isOdd { // value of type 'Double' has no member 'isWholeNumber'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2!= 0 {
sum += Int(num * num)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2!= 0 {
sum += Int(num * num)
}
}
return sum
}
```
if num % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if num % 2!= 0 { // '=' must have consistent whitespace on both sides
if num % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if num % 2!= 0 { // cannot force unwrap value of non-optional type 'Double'
func doubleTheDifference(lst: [Double]) -> Int {
return lst.reduce(0) {
$0 + ($1.isInt && $1.isOdd? $1 * $1 : 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.reduce(0) {
$0 + ($1.isInt && $1.isOdd? $1 * $1 : 0)
}
}
```
return lst.reduce(0) { // type of expression is ambiguous without a type annotation
$0 + ($1.isInt && $1.isOdd? $1 * $1 : 0) // expected ',' separator
func doubleTheDifference(lst: [Double]) -> Int {
return lst.reduce(0) {
$0 + ($1 % 2!= 0? $1 * $1 : 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.reduce(0) {
$0 + ($1 % 2!= 0? $1 * $1 : 0)
}
}
```
$0 + ($1 % 2!= 0? $1 * $1 : 0) // cannot force unwrap value of non-optional type 'Double'
$0 + ($1 % 2!= 0? $1 * $1 : 0) // '=' must have consistent whitespace on both sides
$0 + ($1 % 2!= 0? $1 * $1 : 0) // cannot convert value of type '((), Double)' to expected argument type 'Int'
$0 + ($1 % 2!= 0? $1 * $1 : 0) // expected ',' separator
$0 + ($1 % 2!= 0? $1 * $1 : 0) // expression is not assignable: binary operator returns immutable value
$0 + ($1 % 2!= 0? $1 * $1 : 0) // cannot use optional chaining on non-optional value of type 'Int'
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map {
abs($0.element - guess[$0.offset])
}
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map {
abs($0.element - guess[$0.offset])
}
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { (index, value) in
return abs(value - guess[index])
}
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { (index, value) in
return abs(value - guess[index])
}
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { (index, value) in
return abs(value - guess[index])
}
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map { (index, value) in
return abs(value - guess[index])
}
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map {
return abs($0.element - guess[$0.offset])
}
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.enumerated().map {
return abs($0.element - guess[$0.offset])
}
}
```
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionStrength
}
}
return className + "." + strongestExtension
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionStrength
}
}
return className + "." + strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtension = extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return 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
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = className + "." + extension // expected expression after operator
strongestExtension = className + "." + extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return 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
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = className + "." + extension // expected expression after operator
strongestExtension = className + "." + extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionStrength
}
}
return className + "." + strongestExtension
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionStrength
}
}
return className + "." + strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtension = extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionStrength
}
}
return className + "." + strongestExtension
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionStrength
}
}
return className + "." + strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtension = extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return 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
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = className + "." + extension // expected expression after operator
strongestExtension = className + "." + extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return 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
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = className + "." + extension // expected expression after operator
strongestExtension = className + "." + extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return 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
for extension in extensions {
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > strongestExtensionStrength {
strongestExtension = className + "." + extension
strongestExtensionStrength = extensionStrength
}
}
return strongestExtension
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected Sequence expression for for-each loop
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let extensionStrength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
strongestExtension = className + "." + extension // expected expression after operator
strongestExtension = className + "." + extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var strongest = ""
for extension in extensions {
let strength = extension.uppercased().count - extension.lowercased().count
if strength > max {
max = strength
strongest = className + "." + extension
}
}
return strongest
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var strongest = ""
for extension in extensions {
let strength = extension.uppercased().count - extension.lowercased().count
if strength > max {
max = strength
strongest = className + "." + extension
}
}
return strongest
}
```
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
for extension in extensions { // expected pattern
let strength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let strength = extension.uppercased().count - extension.lowercased().count // expected '{' in extension
let strength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let strength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let strength = extension.uppercased().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let strength = extension.uppercased().count - extension.lowercased().count // expected type name in extension declaration
let strength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
let strength = extension.uppercased().count - extension.lowercased().count // expected initial value after '='
strongest = className + "." + extension // expected '{' in extension
strongest = className + "." + extension // expected expression after operator
strongest = className + "." + extension // declaration is only valid at file scope
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0
var strongestExtensionName = ""
var strongestExtensionNameStrength = 0
for extension in extensions {
let extensionName = extension.lowercased()
let extensionNameStrength = extensionName.count - extensionName.uppercased().count
if extensionNameStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionNameStrength
strongestExtensionName = className + "." + extension
strongestExtensionNameStrength = strongestExtensionStrength
} else if extensionNameStrength == strongestExtensionStrength {
if extensionName < strongestExtensionName {
strongestExtension = extension
strongestExtensionStrength = extensionNameStrength
strongestExtensionName = className + "." + extension
strongestExtensionNameStrength = strongestExtensionStrength
}
}
}
return strongestExtensionName
}
```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
var strongestExtensionName = ""
var strongestExtensionNameStrength = 0
for extension in extensions {
let extensionName = extension.lowercased()
let extensionNameStrength = extensionName.count - extensionName.uppercased().count
if extensionNameStrength > strongestExtensionStrength {
strongestExtension = extension
strongestExtensionStrength = extensionNameStrength
strongestExtensionName = className + "." + extension
strongestExtensionNameStrength = strongestExtensionStrength
} else if extensionNameStrength == strongestExtensionStrength {
if extensionName < strongestExtensionName {
strongestExtension = extension
strongestExtensionStrength = extensionNameStrength
strongestExtensionName = className + "." + extension
strongestExtensionNameStrength = strongestExtensionStrength
}
}
}
return strongestExtensionName
}
```
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
let extensionName = extension.lowercased() // expected '{' in extension
let extensionName = extension.lowercased() // expected type name in extension declaration
let extensionName = extension.lowercased() // consecutive statements on a line must be separated by ';'
let extensionName = extension.lowercased() // expected initial value after '='
let extensionName = extension.lowercased() // declaration is only valid at file scope
strongestExtension = extension // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtensionStrength = extensionNameStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionStrength = extensionNameStrength // expected '{' in extension
strongestExtensionName = className + "." + extension // declaration is only valid at file scope
strongestExtensionNameStrength = strongestExtensionStrength // expected '{' in extension
strongestExtensionNameStrength = strongestExtensionStrength // cannot find type 'strongestExtensionNameStrength' in scope
strongestExtension = extension // expected expression in assignment
strongestExtension = extension // declaration is only valid at file scope
strongestExtensionStrength = extensionNameStrength // expected '{' in extension
strongestExtensionStrength = extensionNameStrength // cannot find type 'strongestExtensionStrength' in scope
strongestExtensionName = className + "." + extension // declaration is only valid at file scope
strongestExtensionNameStrength = strongestExtensionStrength // cannot find type 'strongestExtensionNameStrength' in scope
strongestExtensionNameStrength = strongestExtensionStrength // expected '{' in extension
func cycpatternCheck(a: String, b: String) -> Bool {
return true
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
return true
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
return (a + a).contains(b)
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
return (a + a).contains(b)
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
return a.lowercased().contains(b.lowercased()) || b.lowercased().contains(a.lowercased())
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
return a.lowercased().contains(b.lowercased()) || b.lowercased().contains(a.lowercased())
}
```
// XCTAssertTrue failed
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var a = a
var b = b
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww =
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var temp = ""
for i in 0...a.count - 1 {
temp = a.substring(from: a.index(a.startIndex, offsetBy: i)) + a.substring(from: a.index(a.startIndex, offsetBy: 0))
if temp.contains(b) {
result = true
break
}
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var temp = ""
for i in 0...a.count - 1 {
temp = a.substring(from: a.index(a.startIndex, offsetBy: i)) + a.substring(from: a.index(a.startIndex, offsetBy: 0))
if temp.contains(b) {
result = true
break
}
}
return result
}
```
temp = a.substring(from: a.index(a.startIndex, offsetBy: i)) + a.substring(from: a.index(a.startIndex, offsetBy: 0)) // 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
temp = a.substring(from: a.index(a.startIndex, offsetBy: i)) + a.substring(from: a.index(a.startIndex, offsetBy: 0)) // 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
return a.count == b.count && (a.count == 0 || (a.count > 0 && (a.count == b.count && a.count == b.count && a.count == b.count)))
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
return a.count == b.count && (a.count == 0 || (a.count > 0 && (a.count == b.count && a.count == b.count && a.count == b.count)))
}
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
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
if a == b {
return true
}
if a.count < b.count {
return false
}
for i in 0..<a.count {
if a.substring(from: i, to: a.count) == b {
return true
}
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
if a == b {
return true
}
if a.count < b.count {
return false
}
for i in 0..<a.count {
if a.substring(from: i, to: a.count) == b {
return true
}
}
return false
}
```
if a.substring(from: i, to: a.count) == b { // cannot convert value of type 'Int' to expected argument type 'String.Index'
if a.substring(from: i, to: a.count) == b { // extra argument 'to' in call
```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 i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var www = 0
var xxx = 0
var yyy = 0
var zzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var sss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwww =
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.lowercased()
let b = b.lowercased()
let bLength = b.count
let aLength = a.count
var isSubstring = false
for i in 0..<aLength {
let j = i
let k = j + bLength
if k > aLength {
break
}
let sub = a[a.index(a.startIndex, offsetBy: j)..<a.index(a.startIndex, offsetBy: k)]
if sub == b {
isSubstring = true
break
}
}
return isSubstring
}
```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.lowercased()
let b = b.lowercased()
let bLength = b.count
let aLength = a.count
var isSubstring = false
for i in 0..<aLength {
let j = i
let k = j + bLength
if k > aLength {
break
}
let sub = a[a.index(a.startIndex, offsetBy: j)..<a.index(a.startIndex, offsetBy: k)]
if sub == b {
isSubstring = true
break
}
}
return isSubstring
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var b = b
for i in 0..<a.count {
b = b.substring(from: b.index(b.startIndex, offsetBy: i))
if a.contains(b) {
result = true
break
}
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var b = b
for i in 0..<a.count {
b = b.substring(from: b.index(b.startIndex, offsetBy: i))
if a.contains(b) {
result = true
break
}
}
return result
}
```
b = b.substring(from: b.index(b.startIndex, offsetBy: i)) // 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
// Fatal error: String index is out of bounds
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num!= 0 {
if num % 2 == 0 {
even += 1
} else {
odd += 1
}
num = num / 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num!= 0 {
if num % 2 == 0 {
even += 1
} else {
odd += 1
}
num = num / 10
}
return (even, odd)
}
```
while num!= 0 { // '=' must have consistent whitespace on both sides
while num!= 0 { // cannot force unwrap value of non-optional type 'Int'
while num!= 0 { // use of '=' in a boolean context, did you mean '=='?
func evenOddCount(num: Int) -> (Int, Int) {
let digits = String(num).map { Int(String($0))! }
return (digits.filter { $0 % 2 == 0 }.count, digits.filter { $0 % 2!= 0 }.count)
}
```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 digits = String(num).map { Int(String($0))! }
return (digits.filter { $0 % 2 == 0 }.count, digits.filter { $0 % 2!= 0 }.count)
}
```
return (digits.filter { $0 % 2 == 0 }.count, digits.filter { $0 % 2!= 0 }.count) // '=' must have consistent whitespace on both sides
return (digits.filter { $0 % 2 == 0 }.count, digits.filter { $0 % 2!= 0 }.count) // expression is not assignable: binary operator returns immutable value
return (digits.filter { $0 % 2 == 0 }.count, digits.filter { $0 % 2!= 0 }.count) // cannot convert value of type '()' to closure result type 'Bool'
return (digits.filter { $0 % 2 == 0 }.count, digits.filter { $0 % 2!= 0 }.count) // cannot force unwrap value of non-optional type 'Int'
func evenOddCount(num: Int) -> (Int, Int) {
return (num.description.filter { $0 == "1" }.count, num.description.filter { $0 == "0" }.count)
}
```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) {
return (num.description.filter { $0 == "1" }.count, num.description.filter { $0 == "0" }.count)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.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 even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.count
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.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 even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.count
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
return (num.description.filter { $0.isDigit }.count / 2, num.description.filter { $0.isDigit }.count % 2)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
return (num.description.filter { $0.isDigit }.count / 2, num.description.filter { $0.isDigit }.count % 2)
}
```
return (num.description.filter { $0.isDigit }.count / 2, num.description.filter { $0.isDigit }.count % 2) // value of type 'String.Element' (aka 'Character') has no member 'isDigit'
return (num.description.filter { $0.isDigit }.count / 2, num.description.filter { $0.isDigit }.count % 2) // value of type 'String.Element' (aka 'Character') has no member 'isDigit'
func evenOddCount(num: Int) -> (Int, Int) {
let even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.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 even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.count
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
return (num.description.filter { $0 == "1" }.count, num.description.filter { $0 == "0" }.count)
}
```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) {
return (num.description.filter { $0 == "1" }.count, num.description.filter { $0 == "0" }.count)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
return (num.description.filter { $0 == "1" }.count, num.description.filter { $0 == "0" }.count)
}
```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) {
return (num.description.filter { $0 == "1" }.count, num.description.filter { $0 == "0" }.count)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.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 even = num.description.filter { $0.isWholeNumber }.count
let odd = num.description.filter { $0.isWholeNumber == false }.count
return (even, odd)
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<values.count {
while number >= values[i] {
result += roman[i]
number -= values[i]
}
}
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 = ""
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<values.count {
while number >= values[i] {
result += roman[i]
number -= values[i]
}
}
return result
}
```
number -= values[i] // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
```
func intToMiniRoman(number: Int) -> String {
var result = ""
var number = number
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<arabic.count {
while number >= arabic[i] {
result += roman[i]
number -= arabic[i]
}
}
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 roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<arabic.count {
while number >= arabic[i] {
result += roman[i]
number -= arabic[i]
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
let romanNumerals = [
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
]
for (roman, value) in romanNumerals {
let quotient = number / value
result += String(repeating: roman, count: quotient)
number -= value * quotient
}
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 = ""
let romanNumerals = [
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
]
for (roman, value) in romanNumerals {
let quotient = number / value
result += String(repeating: roman, count: quotient)
number -= value * quotient
}
return result
}
```
number -= value * quotient // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
// TODO: Implement this function
return ""
}
```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 {
// TODO: Implement this function
return ""
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var roman = ""
var num = number
while num > 0 {
if num >= 1000 {
roman += "m"
num -= 1000
} else if num >= 900 {
roman += "cm"
num -= 900
} else if num >= 500 {
roman += "d"
num -= 500
} else if num >= 400 {
roman += "cd"
num -= 400
} else if num >= 100 {
roman += "c"
num -= 100
} else if num >= 90 {
roman += "xc"
num -= 90
} else if num >= 50 {
roman += "l"
num -= 50
} else if num >= 40 {
roman += "xl"
num -= 40
} else if num >= 10 {
roman += "x"
num -= 10
} else if num >= 9 {
roman += "ix"
num -= 9
} else if num >= 5 {
roman += "v"
num -= 5
} else if num >= 4 {
roman += "iv"
num -= 4
} else {
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 = ""
var num = number
while num > 0 {
if num >= 1000 {
roman += "m"
num -= 1000
} else if num >= 900 {
roman += "cm"
num -= 900
} else if num >= 500 {
roman += "d"
num -= 500
} else if num >= 400 {
roman += "cd"
num -= 400
} else if num >= 100 {
roman += "c"
num -= 100
} else if num >= 90 {
roman += "xc"
num -= 90
} else if num >= 50 {
roman += "l"
num -= 50
} else if num >= 40 {
roman += "xl"
num -= 40
} else if num >= 10 {
roman += "x"
num -= 10
} else if num >= 9 {
roman += "ix"
num -= 9
} else if num >= 5 {
roman += "v"
num -= 5
} else if num >= 4 {
roman += "iv"
num -= 4
} else {
roman += "i"
num -= 1
}
}
return roman
}
```
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<values.count {
while num >= values[i] {
result += roman[i]
num -= values[i]
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<values.count {
while num >= values[i] {
result += roman[i]
num -= values[i]
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<arabic.count {
while num >= arabic[i] {
result += roman[i]
num -= arabic[i]
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<arabic.count {
while num >= arabic[i] {
result += roman[i]
num -= arabic[i]
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
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, roman) in romanNumerals {
while number >= value {
result += roman
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 = ""
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, roman) in romanNumerals {
while number >= value {
result += roman
number -= value
}
}
return result
}
```
number -= value // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = [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 roman {
while num >= key {
result += value
num -= key
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
let roman = [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 roman {
while num >= key {
result += value
num -= key
}
}
return result
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return 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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
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 {
return false
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
for char in word {
if!word.contains(char) {
count += 1
}
}
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
for char in word {
if!word.contains(char) {
count += 1
}
}
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
```
if!word.contains(char) { // expected expression, var, or let in 'if' condition
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let uniqueChars = Set(word)
if uniqueChars.count > max {
max = 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 max = 0
var maxWord = ""
for word in words {
let uniqueChars = Set(word)
if uniqueChars.count > max {
max = uniqueChars.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var unique = Set<Character>()
for char in word {
unique.insert(char)
}
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var unique = Set<Character>()
for char in word {
unique.insert(char)
}
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word).count
if unique > max {
max = unique
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 unique = Set(word).count
if unique > max {
max = unique
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var unique = Set<Character>()
for char in word {
unique.insert(char)
}
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var unique = Set<Character>()
for char in word {
unique.insert(char)
}
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let uniqueChars = Set(word)
if uniqueChars.count > max {
max = 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 max = 0
var maxWord = ""
for word in words {
let uniqueChars = Set(word)
if uniqueChars.count > max {
max = uniqueChars.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var uniqueChars = Set<Character>()
for char in word {
uniqueChars.insert(char)
}
if uniqueChars.count > max {
max = 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 max = 0
var maxWord = ""
for word in words {
var uniqueChars = Set<Character>()
for char in word {
uniqueChars.insert(char)
}
if uniqueChars.count > max {
max = uniqueChars.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let unique = Set(word)
if unique.count > max {
max = unique.count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + remaining
var result = [total, remaining]
if total < need {
result[0] = need
result[1] = 0
} else {
result[0] = need
result[1] = total - need
}
return result
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + remaining
var result = [total, remaining]
if total < need {
result[0] = need
result[1] = 0
} else {
result[0] = need
result[1] = total - need
}
return result
}
```
var total = number + remaining // variable 'total' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var remaining = remaining
var result = [Int]()
while eaten < need {
eaten += 1
remaining -= 1
}
result.append(eaten)
result.append(remaining)
return result
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var remaining = remaining
var result = [Int]()
while eaten < need {
eaten += 1
remaining -= 1
}
result.append(eaten)
result.append(remaining)
return result
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
return [number + need, remaining - need]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + remaining
var eaten = 0
var left = 0
while eaten < need {
eaten += 1
total -= 1
left += 1
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + remaining
var eaten = 0
var left = 0
while eaten < need {
eaten += 1
total -= 1
left += 1
}
return [total, left]
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
}
return String($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 {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
}
return String($0)
}.joined()
}
```
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot convert value of type 'String' to expected argument type 'String.Encoding'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // initializer 'init(bytes:encoding:)' requires that 'Bool?' conform to 'Sequence'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // missing argument labels 'bytes:encoding:' in call
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // expected ',' separator
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUpper? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isUpper? char.lowercased() : char.uppercased())
} else {
result.append(char)
}
}
return result
}
```
result.append(char.isUpper? char.lowercased() : char.uppercased()) // expected ',' separator
result.append(char.isUpper? char.lowercased() : char.uppercased()) // type of expression is ambiguous without a type annotation
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
} else {
return String($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 {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
} else {
return String($0)
}
}.joined()
}
```
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot convert value of type 'String' to expected argument type 'String.Encoding'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // initializer 'init(bytes:encoding:)' requires that 'Bool?' conform to 'Sequence'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // missing argument labels 'bytes:encoding:' in call
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // expected ',' separator
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0).uppercased()
}
return String($0).lowercased()
}.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 {
return String($0).uppercased()
}
return String($0).lowercased()
}.joined()
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0).uppercased()
} else {
return String($0).lowercased()
}
}.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 {
return String($0).uppercased()
} else {
return String($0).lowercased()
}
}.joined()
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
return s.map { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $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 { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $0 }.joined()
}
```
return s.map { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $0 }.joined() // consecutive statements on a line must be separated by ';'
return s.map { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $0 }.joined() // cannot use optional chaining on non-optional value of type 'Bool'
return s.map { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $0 }.joined() // consecutive statements on a line must be separated by ';'
return s.map { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $0 }.joined() // expected expression
return s.map { $0.isLetter? $0.isUppercase? $0.lowercased() : $0.uppercased() : $0 }.joined() // consecutive statements on a line must be separated by ';'
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
}
return String($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 {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
}
return String($0)
}.joined()
}
```
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot convert value of type 'String' to expected argument type 'String.Encoding'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // initializer 'init(bytes:encoding:)' requires that 'Bool?' conform to 'Sequence'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // missing argument labels 'bytes:encoding:' in call
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // expected ',' separator
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
} else {
return String($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 {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
} else {
return String($0)
}
}.joined()
}
```
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot convert value of type 'String' to expected argument type 'String.Encoding'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // initializer 'init(bytes:encoding:)' requires that 'Bool?' conform to 'Sequence'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // missing argument labels 'bytes:encoding:' in call
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // expected ',' separator
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
} else {
return String($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 {
return String($0.isUppercase? $0.lowercased() : $0.uppercased())
} else {
return String($0)
}
}.joined()
}
```
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot convert value of type 'String' to expected argument type 'String.Encoding'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // initializer 'init(bytes:encoding:)' requires that 'Bool?' conform to 'Sequence'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // cannot use optional chaining on non-optional value of type 'Bool'
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // missing argument labels 'bytes:encoding:' in call
return String($0.isUppercase? $0.lowercased() : $0.uppercased()) // expected ',' separator
func solve(s: String) -> String {
return s.map {
if $0.isLetter {
return String($0).uppercased()
} else {
return String($0).lowercased()
}
}.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 {
return String($0).uppercased()
} else {
return String($0).lowercased()
}
}.joined()
}
```
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
// TODO: Implement this function
}
```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? {
// TODO: Implement this function
}
```
} // missing return in global function expected to return 'String?'
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let digest = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest)
return digest
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let digest = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest)
return digest
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
CC_MD5(bytes.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? {
// TODO: Implement this function.
return nil
}
```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? {
// TODO: Implement this function.
return nil
}
```
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
// TODO: Implement this function
return nil
}
```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? {
// TODO: Implement this function
return nil
}
```
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
return text.md5
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
return text.md5
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
return text.md5 // value of type 'String' has no member 'md5'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = text.data(using:.utf8)
let hash = data?.md5()
return hash?.hexEncodedString()
}
```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 hash = data?.md5()
return hash?.hexEncodedString()
}
```
let hash = data?.md5() // value of type 'Data' has no member 'md5'
import CommonCrypto
func stringToMd5(text: String) -> String? {
return text.isEmpty? nil : text.md5
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
return text.isEmpty? nil : text.md5
}
```
return text.isEmpty? nil : text.md5 // type of expression is ambiguous without a type annotation
return text.isEmpty? nil : text.md5 // consecutive statements on a line must be separated by ';'
return text.isEmpty? nil : text.md5 // consecutive statements on a line must be separated by ';'
return text.isEmpty? nil : text.md5 // expected expression
return text.isEmpty? nil : text.md5 // 'nil' requires a contextual type
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)!
let digest = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var digest = [UInt8](repeating: 0, count:Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest)
return 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)!
let digest = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var digest = [UInt8](repeating: 0, count:Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest)
return digest
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
CC_MD5(bytes.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? {
// TODO: Implement this function.
}
```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? {
// TODO: Implement this function.
}
```
} // missing return in global function expected to return 'String?'
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)
let digest = data?.withUnsafeBytes {
return $0.baseAddress?.withMemoryRebound(to: UInt8.self, capacity: 16, {
return CC_MD5($0, CC_LONG(data!.count), $1)
})
}
return digest?.map { String(format: "%02hhx", $0) }.joined()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard!text.isEmpty else { return nil }
let data = text.data(using:.utf8)
let digest = data?.withUnsafeBytes {
return $0.baseAddress?.withMemoryRebound(to: UInt8.self, capacity: 16, {
return CC_MD5($0, CC_LONG(data!.count), $1)
})
}
return digest?.map { String(format: "%02hhx", $0) }.joined()
}
```
guard!text.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
return $0.baseAddress?.withMemoryRebound(to: UInt8.self, capacity: 16, { // contextual closure type '(UnsafePointer<UInt8>) throws -> UnsafeMutablePointer<UInt8>?' expects 1 argument, but 2 were used in closure body
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] {
return []
}
```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] {
return []
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
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