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 {
var sorted = numbers.sorted()
for i in 0..<sorted.count-1 {
if sorted[i+1] - sorted[i] < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers.sorted()
for i in 0..<sorted.count-1 {
if sorted[i+1] - sorted[i] < threshold {
return true
}
}
return false
}
```
var sorted = numbers.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sortedNumbers = numbers.sorted()
for (index, number) in sortedNumbers.enumerated() {
if index == sortedNumbers.count - 1 {
break
}
let nextNumber = sortedNumbers[index + 1]
if abs(number - nextNumber) < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sortedNumbers = numbers.sorted()
for (index, number) in sortedNumbers.enumerated() {
if index == sortedNumbers.count - 1 {
break
}
let nextNumber = sortedNumbers[index + 1]
if abs(number - nextNumber) < threshold {
return true
}
}
return false
}
```
var sortedNumbers = numbers.sorted() // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers.sorted()
for i in 0..<sorted.count-1 {
let diff = sorted[i+1] - sorted[i]
if diff < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers.sorted()
for i in 0..<sorted.count-1 {
let diff = sorted[i+1] - sorted[i]
if diff < threshold {
return true
}
}
return false
}
```
var sorted = numbers.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers.sorted()
for i in 0..<sorted.count-1 {
if sorted[i+1] - sorted[i] < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers.sorted()
for i in 0..<sorted.count-1 {
if sorted[i+1] - sorted[i] < threshold {
return true
}
}
return false
}
```
var sorted = numbers.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
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 minDistance = Double.infinity
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
minDistance = min(minDistance, distance)
}
}
return minDistance < threshold
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var minDistance = Double.infinity
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
minDistance = min(minDistance, distance)
}
}
return minDistance < threshold
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
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 sortedNumbers = numbers
sortedNumbers.sort()
for i in 0..<sortedNumbers.count - 1 {
let currentNumber = sortedNumbers[i]
let nextNumber = sortedNumbers[i + 1]
if abs(currentNumber - nextNumber) <= threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sortedNumbers = numbers
sortedNumbers.sort()
for i in 0..<sortedNumbers.count - 1 {
let currentNumber = sortedNumbers[i]
let nextNumber = sortedNumbers[i + 1]
if abs(currentNumber - nextNumber) <= threshold {
return true
}
}
return false
}
```
func separateParenGroups(parenString: String) -> [String] {
var stack = [Character]()
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
stack.append(char)
currentGroup += String(char)
} else if char == ")" {
if stack.isEmpty {
// Invalid input, ignore this character
} else {
stack.removeLast()
currentGroup += String(char)
}
} else if char == " " {
// Ignore spaces
} else {
currentGroup += String(char)
}
if stack.isEmpty {
groups.append(currentGroup)
currentGroup = ""
}
}
return groups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var stack = [Character]()
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
stack.append(char)
currentGroup += String(char)
} else if char == ")" {
if stack.isEmpty {
// Invalid input, ignore this character
} else {
stack.removeLast()
currentGroup += String(char)
}
} else if char == " " {
// Ignore spaces
} else {
currentGroup += String(char)
}
if stack.isEmpty {
groups.append(currentGroup)
currentGroup = ""
}
}
return groups
}
```
// 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 stringArray = parenString.components(separatedBy: " ")
var stringArray2 = [String]()
var stringArray3 = [String]()
var stringArray4 = [String]()
var stringArray5 = [String]()
var stringArray6 = [String]()
var stringArray7 = [String]()
var stringArray8 = [String]()
var stringArray9 = [String]()
var stringArray10 = [String]()
var stringArray11 = [String]()
var stringArray12 = [String]()
var stringArray13 = [String]()
var stringArray14 = [String]()
var stringArray15 = [String]()
var stringArray16 = [String]()
var stringArray17 = [String]()
var stringArray18 = [String]()
var stringArray19 = [String]()
var stringArray20 = [String]()
var stringArray21 = [String]()
var stringArray22 = [String]()
var stringArray23 = [String]()
var stringArray24 = [String]()
var stringArray25 = [String]()
var stringArray26 = [String]()
var stringArray27 = [String]()
var stringArray28 = [String]()
var stringArray29 = [String]()
var stringArray30 = [String]()
var stringArray31 = [String]()
var stringArray32 = [String]()
var stringArray33 = [String]()
var stringArray34 = [String]()
var stringArray35 = [String]()
var stringArray36 = [String]()
var stringArray37 = [String]()
var stringArray38 = [String]()
var stringArray39 = [String]()
var stringArray40 = [String]()
var stringArray41 = [String]()
var stringArray42 = [String]()
var stringArray43 = [String]()
var stringArray44 = [String]()
var stringArray45 = [String]()
var stringArray46 = [String]()
var stringArray47 = [String]()
var stringArray48 = [String]()
var stringArray49 = [String]()
var stringArray50 = [String]()
var stringArray51 = [String]()
var stringArray52 = [String]()
var stringArray53 = [String]()
var stringArray54 = [String]()
var stringArray55 = [String]()
var stringArray56 = [String]()
var stringArray57 = [String]()
var stringArray58 = [String]()
var stringArray59 = [String]()
var stringArray60 = [String]()
var stringArray61 = [String]()
var stringArray62 = [String]()
var stringArray63 = [String]()
var stringArray64 = [String]()
var stringArray65 = [String]()
var stringArray66 = [String]()
var stringArray67 = [String]()
var stringArray68 = [String]()
var stringArray69 = [String]()
var stringArray70 = [String]()
var stringArray71 = [String]()
var stringArray72 = [String]()
var stringArray73 = [String]()
var stringArray74 = [String]()
var stringArray75 = [String]()
var stringArray76 = [String]()
var stringArray77 = [String]()
var stringArray78 = [String]()
var stringArray79 = [String]()
var stringArray80 = [String]()
var stringArray81 = [String]()
var stringArray82 = [String]()
var stringArray83 = [String]()
var stringArray84 = [String]()
var stringArray85 = [String]()
var stringArray86 = [String]()
var stringArray87 = [String]()
var stringArray88 = [String]()
var stringArray89 = [String]()
var stringArray90 = [String]()
var stringArray91 = [String]()
var stringArray92 = [String]()
var stringArray93 = [String]()
var string
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 result = [String]()
var currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 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 currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 0
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var openParenCount = 0
var closeParenCount = 0
for char in parenString {
if char == "(" {
openParenCount += 1
currentString += String(char)
} else if char == ")" {
closeParenCount += 1
currentString += String(char)
}
if openParenCount == closeParenCount {
result.append(currentString)
currentString = ""
openParenCount = 0
closeParenCount = 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 currentString = ""
var openParenCount = 0
var closeParenCount = 0
for char in parenString {
if char == "(" {
openParenCount += 1
currentString += String(char)
} else if char == ")" {
closeParenCount += 1
currentString += String(char)
}
if openParenCount == closeParenCount {
result.append(currentString)
currentString = ""
openParenCount = 0
closeParenCount = 0
}
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentString: String = ""
var openParens: Int = 0
for char in parenString {
if char == "(" {
openParens += 1
currentString += String(char)
} else if char == ")" {
openParens -= 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(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: String = ""
var openParens: Int = 0
for char in parenString {
if char == "(" {
openParens += 1
currentString += String(char)
} else if char == ")" {
openParens -= 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openParens == 0 {
result.append(currentString)
currentString = ""
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 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 currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 0
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var stack = [Character]()
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
stack.append(char)
currentGroup.append(char)
} else if char == ")" {
stack.append(char)
currentGroup.append(char)
if stack.count == 0 {
groups.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
return groups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var stack = [Character]()
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
stack.append(char)
currentGroup.append(char)
} else if char == ")" {
stack.append(char)
currentGroup.append(char)
if stack.count == 0 {
groups.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
return groups
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var stack = [Character]()
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
stack.append(char)
currentGroup += String(char)
} else if char == ")" {
if stack.isEmpty {
groups.append(currentGroup)
currentGroup = ""
} else {
stack.popLast()
currentGroup += String(char)
}
} else {
currentGroup += String(char)
}
}
if !stack.isEmpty {
groups.append(currentGroup)
}
return groups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var stack = [Character]()
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
stack.append(char)
currentGroup += String(char)
} else if char == ")" {
if stack.isEmpty {
groups.append(currentGroup)
currentGroup = ""
} else {
stack.popLast()
currentGroup += String(char)
}
} else {
currentGroup += String(char)
}
}
if !stack.isEmpty {
groups.append(currentGroup)
}
return groups
}
```
stack.popLast() // result of call to 'popLast()' is unused
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 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 currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 0
}
}
return result
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 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 currentString = ""
var openCount = 0
var closeCount = 0
for char in parenString {
if char == "(" {
openCount += 1
currentString += String(char)
} else if char == ")" {
closeCount += 1
currentString += String(char)
} else if char == " " {
continue
} else {
currentString += String(char)
}
if openCount == closeCount {
result.append(currentString)
currentString = ""
openCount = 0
closeCount = 0
}
}
return result
}
```
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
func truncateNumber(number: Double) -> Double {
return Int(number)
}
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return Int(number) // cannot convert return expression of type 'Int' to return type 'Double'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
func truncateNumber(number: Double) -> Double {
return Int(number)
}
func truncateNumber(number: Double) -> Double {
return floor(number)
}
func truncateNumber(number: Double) -> Double {
return ceil(number)
}
func truncateNumber(number: Double) -> Double {
return round(number)
}
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return ceil(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return round(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return Int(number) // cannot convert return expression of type 'Int' to return type 'Double'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(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 - Int(number)
}
func truncateNumber(number: Double) -> Double {
return Int(number)
}
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number - truncateNumber(number: number)
}
// Given a positive floating
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return Int(number) // cannot convert return expression of type 'Int' to return type 'Double'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double {
return number - floor(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - floor(number)
}
```
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
```
func truncateNumber(number: Double) -> Double {
return number - floor(number)
}
func truncateNumber(number: Double) -> Double {
return 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)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(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)
}
func truncateInteger(number: Double) -> Double {
return floor(number)
}
func truncateDecimal(number: Double) -> Double {
return number - floor(number)
}
func truncateNumber(number: Double) -> Double {
return 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)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateInteger(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateDecimal(number: Double) -> Double {
return number - floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateInteger(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateDecimal(number: Double) -> Double {
return number - floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateInteger(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateDecimal(number: Double) -> Double {
return number - floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return floor(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double {
let intPart = Int(number)
return number - Double(intPart)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let intPart = Int(number)
return number - Double(intPart)
}
```
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)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(numbers.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Median Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Median Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Median Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(numbers.count)
}
//
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Median Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let deviations = numbers.map { abs($0 - mean) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Median Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let deviations = numbers.map { abs($0 - median) }
return deviations.reduce(0, +) / Double(deviations.count)
}
// For a given array of
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.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.0, +) / Double(numbers.count)
return numbers.reduce(0.0) {
$0 + abs($1 - mean)
} / Double(numbers.count)
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let absoluteDifferences = numbers.map { abs($0 - mean) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let absoluteDifferences = numbers.map { abs($0 - mean) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let absoluteDifferences = numbers.map { abs($0 - median) }
return absoluteDifferences.reduce(0, +) / 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)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)
}
func meanAbsoluteDeviationAroundMedian(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let mean = numbers.reduce(0, +) / Double(numbers.count)
return (numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)) +
(numbers.reduce(0) { $0 + abs($1 - mean) } / Double(numbers.count))
}
func medianAbsoluteDeviationAroundMean(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let mean = numbers.reduce(0, +) / Double(numbers.count)
return (numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)) +
(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)
}
// For a given array of input numbers, calculate the Median Absolute
// Deviation around the median of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviationAroundMedian(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let mean = numbers.reduce(0, +) / Double(numbers.count)
return (numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)) +
(numbers.reduce(0) { $0 + abs($1 - mean) } / Double(numbers.count))
}
// For a given array of input numbers, calculate the Median Absolute
// Deviation around the mean of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviationAroundMean(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let mean = numbers.reduce(0, +) / Double(numbers.count)
return (numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)) +
(numbers.reduce(0) { $0 + abs($1 - mean) } / Double(numbers.count))
}
// For a given array of input numbers, calculate the Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviationAroundMedian(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let mean = numbers.reduce(0, +) / Double(numbers.count)
return (numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)) +
(numbers.reduce(0) { $0 + abs($1 - mean) } / Double(numbers.count))
}
// For a given array of input numbers, calculate the Median Absolute
// Deviation around the mean of this dataset.
// Median Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviationAroundMean(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let mean = numbers.reduce(0, +) / Double(numbers.count)
return (numbers.reduce(0) { $0 + abs($1 - median) } / Double(numbers.count)) +
(numbers.reduce(0) { $0 + abs($1 - mean) } / Double(numbers.count))
}
// For a given array
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.enumerated() {
result.append(number)
if numberIndex == index {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// insert(numbers: [1, 2, 3], index: 1, delimeter: 4) == [1, 4, 2, 3]
func insert(numbers: [Int], index: Int, delimeter: Int) -> [Int] {
var result = [Int]()
for (numberIndex, number) in numbers.
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, value) in numbers.enumerated() {
result.append(value)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result: [Int] = []
for (index, value) in numbers.enumerated() {
result.append(value)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Remove all duplicates from array `numbers'
// removeDuplicates(numbers: [1, 2, 3, 1, 2, 3]) == [1, 2, 3]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// Remove all duplicates from array `numbers' and insert a number 'delimeter' between every two consecutive elements of the result array
// intersperse(numbers: removeDuplicates(numbers: [1, 2, 3, 1, 2, 3]), delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Remove all duplicates from array `numbers' and insert a number 'delimeter' between every two consecutive elements of the result array
// intersperse(numbers: removeDuplicates(numbers: [1, 2, 3, 1, 2, 3]), delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Remove all duplicates from array `numbers' and insert a number 'delimeter' between every two consecutive elements of the result array
// intersperse(numbers: removeDuplicates(numbers: [1, 2, 3, 1, 2, 3]), delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Remove all duplicates from array `numbers' and insert a number 'delimeter' between every two consecutive elements of the result array
// intersperse(numbers: removeDuplicates(numbers: [1, 2, 3, 1, 2, 3]), delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Remove all duplicates from array `numbers' and insert a number 'delimeter' between every two consecutive elements of the result array
// intersperse(numbers: removeDuplicates(numbers: [1, 2, 3, 1, 2, 3]), delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Remove all duplicates from array `numbers' and insert a number 'delimeter' between every two consecutive elements of the result array
// intersperse(numbers: removeDuplicates(numbers:
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index != numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index != numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index != numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index != numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (index, number) in numbers.enumerated() {
result.append(number)
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
func parseNestedParens(parenString: String) -> [Int] {
let parenArray = parenString.components(separatedBy: " ")
var result = [Int]()
for str in parenArray {
var max = 0
var count = 0
for char in str {
if char == "(" {
count += 1
} else if char == ")" {
count -= 1
}
max = max(max, count)
}
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] {
let parenArray = parenString.components(separatedBy: " ")
var result = [Int]()
for str in parenArray {
var max = 0
var count = 0
for char in str {
if char == "(" {
count += 1
} else if char == ")" {
count -= 1
}
max = max(max, count)
}
result.append(max)
}
return result
}
```
max = max(max, count) // cannot call value of non-function type 'Int'
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
if char == " " {
result.append(maxDepth)
maxDepth = 0
depth = 0
}
}
result.append(maxDepth)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
if char == " " {
result.append(maxDepth)
maxDepth = 0
depth = 0
}
}
result.append(maxDepth)
return result
}
```
func parseNestedParens(parenString: String) -> [Int] {
let parenArray = parenString.components(separatedBy: " ")
var result = [Int]()
for paren in parenArray {
var maxDepth = 0
var depth = 0
for char in paren {
if char == "(" {
depth += 1
} else if char == ")" {
depth -= 1
}
maxDepth = max(maxDepth, depth)
}
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] {
let parenArray = parenString.components(separatedBy: " ")
var result = [Int]()
for paren in parenArray {
var maxDepth = 0
var depth = 0
for char in paren {
if char == "(" {
depth += 1
} else if char == ")" {
depth -= 1
}
maxDepth = max(maxDepth, depth)
}
result.append(maxDepth)
}
return result
}
```
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var maxDepth = 0
var currentDepth = 0
for char in parenString {
if char == "(" {
currentDepth += 1
maxDepth = max(maxDepth, currentDepth)
} else if char == ")" {
currentDepth -= 1
}
}
result.append(maxDepth)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var maxDepth = 0
var currentDepth = 0
for char in parenString {
if char == "(" {
currentDepth += 1
maxDepth = max(maxDepth, currentDepth)
} else if char == ")" {
currentDepth -= 1
}
}
result.append(maxDepth)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result: [Int] = []
let parenArray = parenString.components(separatedBy: " ")
for paren in parenArray {
var maxDepth = 0
var depth = 0
for char in paren {
if char == "(" {
depth += 1
} else if char == ")" {
depth -= 1
}
maxDepth = max(maxDepth, depth)
}
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] = []
let parenArray = parenString.components(separatedBy: " ")
for paren in parenArray {
var maxDepth = 0
var depth = 0
for char in paren {
if char == "(" {
depth += 1
} else if char == ")" {
depth -= 1
}
maxDepth = max(maxDepth, depth)
}
result.append(maxDepth)
}
return result
}
// Test cases
print(parseNestedParens(parenString: "(()()) ((())) () ((())()())")) // [2, 3, 1, 3]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (())")) // [2, 3, 1, 3, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (())")) // [2, 3, 1, 3, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(parseNestedParens(parenString: "(()()) ((())) () ((())()()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (()) (())")) // [2, 3,
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
let stringArray = parenString.components(separatedBy: " ")
for string in stringArray {
var max = 0
var current = 0
for char in string {
if char == "(" {
current += 1
max = max < current ? current : max
} else if char == ")" {
current -= 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] {
var result = [Int]()
let stringArray = parenString.components(separatedBy: " ")
for string in stringArray {
var max = 0
var current = 0
for char in string {
if char == "(" {
current += 1
max = max < current ? current : max
} else if char == ")" {
current -= 1
}
}
result.append(max)
}
return result
}
```
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var max = 0
var count = 0
for char in parenString {
if char == "(" {
count += 1
max = max < count ? count : max
} 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] {
var result = [Int]()
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var max = 0
var count = 0
for char in parenString {
if char == "(" {
count += 1
max = max < count ? count : max
} else {
count -= 1
}
}
result.append(max)
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
if depth == 0 {
result.append(maxDepth)
maxDepth = 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 maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
if depth == 0 {
result.append(maxDepth)
maxDepth = 0
}
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
if depth == 0 {
result.append(maxDepth)
maxDepth = 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 maxDepth = 0
var depth = 0
var result = [Int]()
for char in parenString {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
if depth == 0 {
result.append(maxDepth)
maxDepth = 0
}
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result: [Int] = []
let parenArray = parenString.components(separatedBy: " ")
for paren in parenArray {
var maxDepth = 0
var depth = 0
for char in paren {
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] = []
let parenArray = parenString.components(separatedBy: " ")
for paren in parenArray {
var maxDepth = 0
var depth = 0
for char in paren {
if char == "(" {
depth += 1
maxDepth = max(maxDepth, depth)
} else if char == ")" {
depth -= 1
}
}
result.append(maxDepth)
}
return result
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```
func filterBySubstring(strings: [String], substring: String) -> [String] {
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) }
}
// 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) }
}
// 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) }
}
// 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) }
}
// 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) }
}
// 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) }
}
// 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) }
}
// 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) }
}
// 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) }
}
// 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 {
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 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 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 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 rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
print(rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]))
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
print(rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]))
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
for number in numbers {
min = min < number ? min : number
result.append(min)
}
return result
}
func rollingAvg(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
for number in numbers {
sum += number
result.append(Double(sum) / Double(numbers.count))
}
return result
}
func rollingMedian(numbers: [Int]) -> [Double] {
var result = [Double]()
var sorted = numbers
sorted.sort()
for number in numbers {
let index = sorted.firstIndex(of: number)!
let median = Double(sorted[index])
result.append(median)
}
return result
}
func rollingMode(numbers: [Int]) -> [Int] {
var result = [Int]()
var modes = [Int: Int]()
for number in numbers {
modes[number] = (modes[number] ?? 0) + 1
result.append(modes.max(by: { $0.value < $1.value })!.key)
}
return result
}
func rollingRange(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var max = Int.min
for number in numbers {
min = min < number ? min : number
max = max > number ? max : number
result.append(max - min)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
// From a given array of integers, generate an array of rolling minimum element found until given moment
// in the sequence.
// rollingMin(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 2, 2, 2, 2, 2]
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
for number in numbers {
min = min < number ? min : number
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling average of elements found until given moment
// in the sequence.
// rollingAvg(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1.5, 2, 2.25, 2.5, 3, 3]
func rollingAvg(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
for number in numbers {
sum += number
result.append(Double(sum) / Double(numbers.count))
}
return result
}
// From a given array of integers, generate an array of rolling median of elements found until given moment
// in the sequence.
// rollingMedian(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1.5, 2, 2, 2.5, 3, 3]
func rollingMedian(numbers: [Int]) -> [Double] {
var result = [Double]()
var sorted = numbers
sorted.sort()
for number in numbers {
let index = sorted.firstIndex(of: number)!
let median = Double(sorted[index])
result.append(median)
}
return result
}
// From a given array of integers, generate an array of rolling mode of elements found until given moment
// in the sequence.
// rollingMode(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 2, 2, 2, 3, 3]
func rollingMode(numbers: [Int]) -> [Int] {
var result = [Int]()
var modes = [Int: Int]()
for number in numbers {
modes[number] = (modes[number] ?? 0) + 1
result.append(modes.max(by: { $0.value < $1.value })!.key)
}
return result
}
// From a given array of integers, generate an array of rolling range of elements found until given moment
// in the sequence.
// rollingRange(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 1, 1, 1, 1, 2]
func rollingRange(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = Int.max
var max = Int.min
for number in numbers {
min = min < number ? min : number
max = max > number ? max : number
result.append(max - min)
}
return result
}
// From a given array of integers, generate an array of rolling variance of elements found until given moment
// in the sequence.
// rollingVariance(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.25, 0.5, 0.5, 0.5, 1, 1]
func rollingVariance(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumOfSquares = 0
for number in numbers {
sum += number
sumOfSquares += number * number
result.append(Double(sumOfSquares) / Double(numbers.count) - Double(sum) * Double(sum) / Double(numbers
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var maxes = [Int]()
var max = Int.min
for number in numbers {
max = max < number ? number : max
maxes.append(max)
}
return maxes
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var maxes = [Int]()
var max = Int.min
for number in numbers {
max = max < number ? number : max
maxes.append(max)
}
return maxes
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
print(rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]))
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int.min
for number in numbers {
max = max > number ? max : number
result.append(max)
}
return result
}
```
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let length = string.count
var i = length - 1
while i > 0 {
let prefix = string.prefix(i)
let suffix = string.suffix(length - i)
if isPalindrome(string: prefix) {
return string + String(suffix.reversed())
}
i -= 1
}
return string + String(string.reversed())
}
func isPalindrome(string: String) -> Bool {
let string = string.lowercased()
let length = string.count
for i in 0..<length / 2 {
if string[string.index(string.startIndex, offsetBy: i)] != string[string.index(string.endIndex, offsetBy: -i - 1)] {
return false
}
}
return true
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let length = string.count
var i = length - 1
while i > 0 {
let prefix = string.prefix(i)
let suffix = string.suffix(length - i)
if isPalindrome(string: prefix) {
return string + String(suffix.reversed())
}
i -= 1
}
return string + String(string.reversed())
}
// isPalindrome(string: "") == true
// isPalindrome(string: "a") == true
// isPalindrome(string: "aa") == true
// isPalindrome(string: "ab") == false
// isPalindrome(string: "aba") == true
// isPalindrome(string: "abba") == true
// isPalindrome(string: "abcba") == true
// isPalindrome(string: "abc") == false
func isPalindrome(string: String) -> Bool {
let string = string.lowercased()
let length = string.count
for i in 0..<length / 2 {
if string[string.index(string.startIndex, offsetBy: i)] != string[string.index(string.endIndex, offsetBy: -i - 1)] {
return false
}
}
return true
}
```
if isPalindrome(string: prefix) { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
var i = 0
var j = stringLength - 1
while i < j {
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] {
i += 1
j -= 1
} else {
break
}
}
let palindromicSuffixStartIndex = i
let palindromicSuffixEndIndex = j
var prefixEndIndex = palindromicSuffixEndIndex
while prefixEndIndex > 0 {
if string[string.startIndex.advancedBy(prefixEndIndex)] == string[string.startIndex.advancedBy(palindromicSuffixStartIndex)] {
prefixEndIndex -= 1
} else {
break
}
}
let prefixStartIndex = prefixEndIndex + 1
let palindromicSuffix = string.suffix(stringLength - palindromicSuffixEndIndex)
let prefix = string.prefix(prefixEndIndex)
return String(palindromicSuffix) + String(prefix.reverse())
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
var i = 0
var j = stringLength - 1
while i < j {
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] {
i += 1
j -= 1
} else {
break
}
}
let palindromicSuffixStartIndex = i
let palindromicSuffixEndIndex = j
var prefixEndIndex = palindromicSuffixEndIndex
while prefixEndIndex > 0 {
if string[string.startIndex.advancedBy(prefixEndIndex)] == string[string.startIndex.advancedBy(palindromicSuffixStartIndex)] {
prefixEndIndex -= 1
} else {
break
}
}
let prefixStartIndex = prefixEndIndex + 1
let palindromicSuffix = string.suffix(stringLength - palindromicSuffixEndIndex)
let prefix = string.prefix(prefixEndIndex)
return String(palindromicSuffix) + String(prefix.reverse())
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
if string[string.startIndex.advancedBy(prefixEndIndex)] == string[string.startIndex.advancedBy(palindromicSuffixStartIndex)] { // value of type 'String.Index' has no member 'advancedBy'
if string[string.startIndex.advancedBy(prefixEndIndex)] == string[string.startIndex.advancedBy(palindromicSuffixStartIndex)] { // value of type 'String.Index' has no member 'advancedBy'
return String(palindromicSuffix) + String(prefix.reverse()) // value of type 'String.SubSequence' (aka 'Substring') has no member 'reverse'
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
var longestPalindromicSuffixLength = 0
var longestPalindromicSuffixIndex = 0
for i in 0..<stringLength {
var palindromicSuffixLength = 0
for j in 0..<stringLength - i {
if string[string.startIndex.advancedBy(i + j)] == string[string.startIndex.advancedBy(stringLength - j - 1)] {
palindromicSuffixLength += 1
} else {
break
}
}
if palindromicSuffixLength > longestPalindromicSuffixLength {
longestPalindromicSuffixLength = palindromicSuffixLength
longestPalindromicSuffixIndex = i
}
}
let stringPrefix = string[string.startIndex..<string.startIndex.advancedBy(longestPalindromicSuffixIndex)]
let stringSuffix = string[string.startIndex.advancedBy(longestPalindromicSuffixIndex)..<string.startIndex.advancedBy(stringLength)]
let stringPrefixReversed = stringPrefix.reverse()
return stringPrefixReversed + stringSuffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
var longestPalindromicSuffixLength = 0
var longestPalindromicSuffixIndex = 0
for i in 0..<stringLength {
var palindromicSuffixLength = 0
for j in 0..<stringLength - i {
if string[string.startIndex.advancedBy(i + j)] == string[string.startIndex.advancedBy(stringLength - j - 1)] {
palindromicSuffixLength += 1
} else {
break
}
}
if palindromicSuffixLength > longestPalindromicSuffixLength {
longestPalindromicSuffixLength = palindromicSuffixLength
longestPalindromicSuffixIndex = i
}
}
let stringPrefix = string[string.startIndex..<string.startIndex.advancedBy(longestPalindromicSuffixIndex)]
let stringSuffix = string[string.startIndex.advancedBy(longestPalindromicSuffixIndex)..<string.startIndex.advancedBy(stringLength)]
let stringPrefixReversed = stringPrefix.reverse()
return stringPrefixReversed + stringSuffix
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
if string[string.startIndex.advancedBy(i + j)] == string[string.startIndex.advancedBy(stringLength - j - 1)] { // value of type 'String.Index' has no member 'advancedBy'
if string[string.startIndex.advancedBy(i + j)] == string[string.startIndex.advancedBy(stringLength - j - 1)] { // value of type 'String.Index' has no member 'advancedBy'
let stringPrefix = string[string.startIndex..<string.startIndex.advancedBy(longestPalindromicSuffixIndex)] // value of type 'String.Index' has no member 'advancedBy'
let stringSuffix = string[string.startIndex.advancedBy(longestPalindromicSuffixIndex)..<string.startIndex.advancedBy(stringLength)] // value of type 'String.Index' has no member 'advancedBy'
let stringSuffix = string[string.startIndex.advancedBy(longestPalindromicSuffixIndex)..<string.startIndex.advancedBy(stringLength)] // value of type 'String.Index' has no member 'advancedBy'
func makePalindrome(string: String) -> String {
let string = string.characters
let length = string.count
if length == 0 {
return ""
}
var i = length - 1
while i > 0 {
let isPalindrome = isPalindrome(string: string, from: 0, to: i)
if isPalindrome {
break
}
i -= 1
}
let prefixLength = i + 1
let suffixLength = length - prefixLength
let prefix = string[0..<prefixLength]
let suffix = string[prefixLength..<length]
let reversedSuffix = suffix.reverse()
return prefix + reversedSuffix
}
func isPalindrome(string: [Character], from: Int, to: Int) -> Bool {
let length = to - from + 1
for i in 0..<length / 2 {
let firstIndex = from + i
let secondIndex = to - i
if string[firstIndex] != string[secondIndex] {
return false
}
}
return true
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let length = string.count
if length == 0 {
return ""
}
var i = length - 1
while i > 0 {
let isPalindrome = isPalindrome(string: string, from: 0, to: i)
if isPalindrome {
break
}
i -= 1
}
let prefixLength = i + 1
let suffixLength = length - prefixLength
let prefix = string[0..<prefixLength]
let suffix = string[prefixLength..<length]
let reversedSuffix = suffix.reverse()
return prefix + reversedSuffix
}
func isPalindrome(string: [Character], from: Int, to: Int) -> Bool {
let length = to - from + 1
for i in 0..<length / 2 {
let firstIndex = from + i
let secondIndex = to - i
if string[firstIndex] != string[secondIndex] {
return false
}
}
return true
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
let isPalindrome = isPalindrome(string: string, from: 0, to: i) // cannot convert value of type 'String' to expected argument type '[Character]'
let prefix = string[0..<prefixLength] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let suffix = string[prefixLength..<length] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let reversedSuffix = suffix.reverse() // value of type 'String' has no member 'reverse'
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let stringLength = string.count
if stringLength == 0 {
return ""
}
var longestPalindromicSuffixLength = 0
var longestPalindromicSuffixIndex = 0
for i in 0..<stringLength {
var palindromicSuffixLength = 0
for j in stride(from: stringLength - 1, through: i, by: -1) {
if string[string.index(string.startIndex, offsetBy: i)] == string[string.index(string.startIndex, offsetBy: j)] {
palindromicSuffixLength += 1
} else {
break
}
}
if palindromicSuffixLength > longestPalindromicSuffixLength {
longestPalindromicSuffixLength = palindromicSuffixLength
longestPalindromicSuffixIndex = i
}
}
let prefix = string[string.startIndex..<string.index(string.startIndex, offsetBy: longestPalindromicSuffixIndex)]
let suffix = string[string.index(string.startIndex, offsetBy: longestPalindromicSuffixIndex)..<string.endIndex]
return String(prefix) + String(suffix.reversed())
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.lowercased()
let stringLength = string.count
if stringLength == 0 {
return ""
}
var longestPalindromicSuffixLength = 0
var longestPalindromicSuffixIndex = 0
for i in 0..<stringLength {
var palindromicSuffixLength = 0
for j in stride(from: stringLength - 1, through: i, by: -1) {
if string[string.index(string.startIndex, offsetBy: i)] == string[string.index(string.startIndex, offsetBy: j)] {
palindromicSuffixLength += 1
} else {
break
}
}
if palindromicSuffixLength > longestPalindromicSuffixLength {
longestPalindromicSuffixLength = palindromicSuffixLength
longestPalindromicSuffixIndex = i
}
}
let prefix = string[string.startIndex..<string.index(string.startIndex, offsetBy: longestPalindromicSuffixIndex)]
let suffix = string[string.index(string.startIndex, offsetBy: longestPalindromicSuffixIndex)..<string.endIndex]
return String(prefix) + String(suffix.reversed())
}
```
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
var longestPalindromicSuffixLength = 0
var longestPalindromicSuffixIndex = 0
for suffixLength in 0..<stringLength {
let suffixStartIndex = stringLength - suffixLength - 1
var isPalindromic = true
for i in 0..<suffixLength {
if string[suffixStartIndex + i] != string[suffixStartIndex - i] {
isPalindromic = false
break
}
}
if isPalindromic {
longestPalindromicSuffixLength = suffixLength
longestPalindromicSuffixIndex = suffixStartIndex
break
}
}
let prefix = string[0..<longestPalindromicSuffixIndex]
let suffix = string[longestPalindromicSuffixIndex..<stringLength]
let reversedPrefix = String(prefix.reverse())
return reversedPrefix + String(suffix)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
var longestPalindromicSuffixLength = 0
var longestPalindromicSuffixIndex = 0
for suffixLength in 0..<stringLength {
let suffixStartIndex = stringLength - suffixLength - 1
var isPalindromic = true
for i in 0..<suffixLength {
if string[suffixStartIndex + i] != string[suffixStartIndex - i] {
isPalindromic = false
break
}
}
if isPalindromic {
longestPalindromicSuffixLength = suffixLength
longestPalindromicSuffixIndex = suffixStartIndex
break
}
}
let prefix = string[0..<longestPalindromicSuffixIndex]
let suffix = string[longestPalindromicSuffixIndex..<stringLength]
let reversedPrefix = String(prefix.reverse())
return reversedPrefix + String(suffix)
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
if string[suffixStartIndex + i] != string[suffixStartIndex - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[suffixStartIndex + i] != string[suffixStartIndex - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
let prefix = string[0..<longestPalindromicSuffixIndex] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let suffix = string[longestPalindromicSuffixIndex..<stringLength] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let reversedPrefix = String(prefix.reverse()) // value of type 'String' has no member 'reverse'
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
// Find the longest palindromic suffix.
var i = stringLength - 1
var j = stringLength - 1
while i > 0 && string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] {
i -= 1
j -= 1
}
// If the string is already a palindrome, return it.
if i == 0 {
return string
}
// If the string is not a palindrome, append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
let prefix = string[string.startIndex.advancedBy(0)..<string.startIndex.advancedBy(i)]
let suffix = string[string.startIndex.advancedBy(i)..<string.startIndex.advancedBy(j + 1)]
let reversedPrefix = String(prefix.reverse())
return reversedPrefix + String(suffix)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
// Find the longest palindromic suffix.
var i = stringLength - 1
var j = stringLength - 1
while i > 0 && string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] {
i -= 1
j -= 1
}
// If the string is already a palindrome, return it.
if i == 0 {
return string
}
// If the string is not a palindrome, append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
let prefix = string[string.startIndex.advancedBy(0)..<string.startIndex.advancedBy(i)]
let suffix = string[string.startIndex.advancedBy(i)..<string.startIndex.advancedBy(j + 1)]
let reversedPrefix = String(prefix.reverse())
return reversedPrefix + String(suffix)
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
while i > 0 && string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
while i > 0 && string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
let prefix = string[string.startIndex.advancedBy(0)..<string.startIndex.advancedBy(i)] // value of type 'String.Index' has no member 'advancedBy'
let prefix = string[string.startIndex.advancedBy(0)..<string.startIndex.advancedBy(i)] // value of type 'String.Index' has no member 'advancedBy'
let suffix = string[string.startIndex.advancedBy(i)..<string.startIndex.advancedBy(j + 1)] // value of type 'String.Index' has no member 'advancedBy'
let suffix = string[string.startIndex.advancedBy(i)..<string.startIndex.advancedBy(j + 1)] // value of type 'String.Index' has no member 'advancedBy'
func makePalindrome(string: String) -> String {
let string = string.characters
let length = string.count
var i = 0
var j = length - 1
while i < j {
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] {
i += 1
j -= 1
} else {
break
}
}
let prefixLength = i
let suffixLength = length - j - 1
let prefix = string.prefix(prefixLength)
let suffix = string.suffix(suffixLength)
let reversedSuffix = suffix.reverse()
return prefix + reversedSuffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let length = string.count
var i = 0
var j = length - 1
while i < j {
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] {
i += 1
j -= 1
} else {
break
}
}
let prefixLength = i
let suffixLength = length - j - 1
let prefix = string.prefix(prefixLength)
let suffix = string.suffix(suffixLength)
let reversedSuffix = suffix.reverse()
return prefix + reversedSuffix
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
if string[string.startIndex.advancedBy(i)] == string[string.startIndex.advancedBy(j)] { // value of type 'String.Index' has no member 'advancedBy'
let reversedSuffix = suffix.reverse() // value of type 'String.SubSequence' (aka 'Substring') has no member 'reverse'
func makePalindrome(string: String) -> String {
let length = string.count
guard length > 0 else {
return string
}
var left = 0
var right = length - 1
while left < right {
let leftChar = string[string.index(string.startIndex, offsetBy: left)]
let rightChar = string[string.index(string.startIndex, offsetBy: right)]
if leftChar != rightChar {
break
}
left += 1
right -= 1
}
let palindromicSubstring = string[string.index(string.startIndex, offsetBy: left)...string.index(string.startIndex, offsetBy: right)]
let palindromicSubstringLength = palindromicSubstring.count
let prefix = string[string.startIndex..<string.index(string.startIndex, offsetBy: left)]
let prefixLength = prefix.count
let suffix = string[string.index(string.startIndex, offsetBy: right + 1)..<string.endIndex]
let suffixLength = suffix.count
let prefixReversed = String(prefix.reversed())
if palindromicSubstringLength > prefixLength && palindromicSubstringLength > suffixLength {
return string + prefixReversed
} else if palindromicSubstringLength > prefixLength {
return string + prefixReversed
} else if palindromicSubstringLength > suffixLength {
return prefixReversed + string
} else {
return string + prefixReversed
}
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let length = string.count
guard length > 0 else {
return string
}
var left = 0
var right = length - 1
while left < right {
let leftChar = string[string.index(string.startIndex, offsetBy: left)]
let rightChar = string[string.index(string.startIndex, offsetBy: right)]
if leftChar != rightChar {
break
}
left += 1
right -= 1
}
let palindromicSubstring = string[string.index(string.startIndex, offsetBy: left)...string.index(string.startIndex, offsetBy: right)]
let palindromicSubstringLength = palindromicSubstring.count
let prefix = string[string.startIndex..<string.index(string.startIndex, offsetBy: left)]
let prefixLength = prefix.count
let suffix = string[string.index(string.startIndex, offsetBy: right + 1)..<string.endIndex]
let suffixLength = suffix.count
let prefixReversed = String(prefix.reversed())
if palindromicSubstringLength > prefixLength && palindromicSubstringLength > suffixLength {
return string + prefixReversed
} else if palindromicSubstringLength > prefixLength {
return string + prefixReversed
} else if palindromicSubstringLength > suffixLength {
return prefixReversed + string
} else {
return string + prefixReversed
}
}
print(makePalindrome(string: "cat"))
print(makePalindrome(string: "cata"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "racecar"))
print(makePalindrome(string: "
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
// Find the longest palindromic suffix.
var i = stringLength - 1
while i > 0 && string[string.startIndex.advancedBy(i)] != string[string.startIndex.advancedBy(stringLength - 1)] {
i -= 1
}
// If there is no palindromic suffix, return the original string.
if i == 0 {
return string.reduce("", combine: { $0 + String($1) })
}
// If there is a palindromic suffix, append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
var j = stringLength - 1
while j > i && string[string.startIndex.advancedBy(j)] != string[string.startIndex.advancedBy(stringLength - 1 - (j - i))] {
j -= 1
}
let prefix = string.prefix(j)
let suffix = string.suffix(stringLength - j)
return prefix.reduce("", combine: { $0 + String($1) }) + suffix.reverse().reduce("", combine: { $0 + String($1) })
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let string = string.characters
let stringLength = string.count
// Find the longest palindromic suffix.
var i = stringLength - 1
while i > 0 && string[string.startIndex.advancedBy(i)] != string[string.startIndex.advancedBy(stringLength - 1)] {
i -= 1
}
// If there is no palindromic suffix, return the original string.
if i == 0 {
return string.reduce("", combine: { $0 + String($1) })
}
// If there is a palindromic suffix, append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
var j = stringLength - 1
while j > i && string[string.startIndex.advancedBy(j)] != string[string.startIndex.advancedBy(stringLength - 1 - (j - i))] {
j -= 1
}
let prefix = string.prefix(j)
let suffix = string.suffix(stringLength - j)
return prefix.reduce("", combine: { $0 + String($1) }) + suffix.reverse().reduce("", combine: { $0 + String($1) })
}
```
let string = string.characters // 'characters' is unavailable: Please use String directly
while i > 0 && string[string.startIndex.advancedBy(i)] != string[string.startIndex.advancedBy(stringLength - 1)] { // value of type 'String.Index' has no member 'advancedBy'
while i > 0 && string[string.startIndex.advancedBy(i)] != string[string.startIndex.advancedBy(stringLength - 1)] { // value of type 'String.Index' has no member 'advancedBy'
return string.reduce("", combine: { $0 + String($1) }) // extraneous argument label 'combine:' in call
while j > i && string[string.startIndex.advancedBy(j)] != string[string.startIndex.advancedBy(stringLength - 1 - (j - i))] { // value of type 'String.Index' has no member 'advancedBy'
while j > i && string[string.startIndex.advancedBy(j)] != string[string.startIndex.advancedBy(stringLength - 1 - (j - i))] { // value of type 'String.Index' has no member 'advancedBy'
return prefix.reduce("", combine: { $0 + String($1) }) + suffix.reverse().reduce("", combine: { $0 + String($1) }) // extraneous argument label 'combine:' in call
return prefix.reduce("", combine: { $0 + String($1) }) + suffix.reverse().reduce("", combine: { $0 + String($1) }) // value of type 'String.SubSequence' (aka 'Substring') has no member 'reverse'
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.characters.count {
let aChar = a[a.startIndex.advancedBy(i)]
let bChar = b[b.startIndex.advancedBy(i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.characters.count {
let aChar = a[a.startIndex.advancedBy(i)]
let bChar = b[b.startIndex.advancedBy(i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```
for i in 0..<a.characters.count { // 'characters' is unavailable: Please use String directly
let aChar = a[a.startIndex.advancedBy(i)] // value of type 'String.Index' has no member 'advancedBy'
let bChar = b[b.startIndex.advancedBy(i)] // value of type 'String.Index' has no member 'advancedBy'
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = [Character]()
for i in 0..<a.count {
let a = a[i]
let b = b[i]
if a == b {
result.append("0")
} else {
result.append("1")
}
}
return String(result)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = [Character]()
for i in 0..<a.count {
let a = a[i]
let b = b[i]
if a == b {
result.append("0")
} else {
result.append("1")
}
}
return String(result)
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.characters.count {
let aChar = a.characters.dropFirst(i).first!
let bChar = b.characters.dropFirst(i).first!
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.characters.count {
let aChar = a.characters.dropFirst(i).first!
let bChar = b.characters.dropFirst(i).first!
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```
for i in 0..<a.characters.count { // 'characters' is unavailable: Please use String directly
let aChar = a.characters.dropFirst(i).first! // 'characters' is unavailable: Please use String directly
let bChar = b.characters.dropFirst(i).first! // 'characters' is unavailable: Please use String directly
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = [Character]()
for i in 0..<a.count {
if a[i] == b[i] {
result.append("0")
} else {
result.append("1")
}
}
return String(result)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = [Character]()
for i in 0..<a.count {
if a[i] == b[i] {
result.append("0")
} else {
result.append("1")
}
}
return String(result)
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.characters.count {
let aChar = a[a.startIndex.advancedBy(i)]
let bChar = b[b.startIndex.advancedBy(i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.characters.count {
let aChar = a[a.startIndex.advancedBy(i)]
let bChar = b[b.startIndex.advancedBy(i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```
for i in 0..<a.characters.count { // 'characters' is unavailable: Please use String directly
let aChar = a[a.startIndex.advancedBy(i)] // value of type 'String.Index' has no member 'advancedBy'
let bChar = b[b.startIndex.advancedBy(i)] // value of type 'String.Index' has no member 'advancedBy'
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result.append("0")
} else {
result.append("1")
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = ""
for i in 0..<a.count {
let a = Int(String(a[i]))!
let b = Int(String(b[i]))!
if a == b {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = ""
for i in 0..<a.count {
let a = Int(String(a[i]))!
let b = Int(String(b[i]))!
if a == b {
result += "0"
} else {
result += "1"
}
}
return result
}
```
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = [Character]()
for (i, _) in a.enumerated() {
if a[i] == b[i] {
result.append("0")
} else {
result.append("1")
}
}
return String(result)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a)
let b = Array(b)
var result = [Character]()
for (i, _) in a.enumerated() {
if a[i] == b[i] {
result.append("0")
} else {
result.append("1")
}
}
return String(result)
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
let aChar = a[a.index(a.startIndex, offsetBy: i)]
let bChar = b[b.index(b.startIndex, offsetBy: i)]
if aChar == bChar {
result += "0"
} else {
result += "1"
}
}
return result
}
```
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```
func longest(strings: [String]) -> String? {
guard let first = strings.first else { return nil }
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? {
guard let first = strings.first else { return nil }
return strings.max(by: { $0.count < $1.count })
}
```
guard let first = strings.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
func longest(strings: [String]) -> String? {
guard let first = strings.first else { return nil }
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? {
guard let first = strings.first else { return nil }
return strings.max(by: { $0.count < $1.count })
}
```
guard let first = strings.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
func longest(strings: [String]) -> String? {
guard let first = strings.first else { return nil }
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? {
guard let first = strings.first else { return nil }
return strings.max(by: { $0.count < $1.count })
}
```
guard let first = strings.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
func longest2(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
func longest3(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
func longest4(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
func longest5(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
func longest6(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
func longest7(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest2(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest3(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest4(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest5(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest6(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest7(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
// 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 longest8(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else { return nil }
return longest
}
```
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard let longest = strings.max(by: { $0.count < $1.count }) else {
return nil
}
return longest
}
```
func longest(strings: [String]) -> String? {
guard let first = strings.first else { return nil }
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? {
guard let first = strings.first else { return nil }
return strings.max(by: { $0.count < $1.count })
}
```
guard let first = strings.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
func longest(strings: [String]) -> String? {
guard let first = strings.first else { return nil }
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? {
guard let first = strings.first else { return nil }
return strings.max(by: { $0.count < $1.count })
}
```
guard let first = strings.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// TODO: 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 {
if a == b {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
}
return greatestCommonDivisor(a: a, b: b - a)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == b {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
}
return greatestCommonDivisor(a: a, b: b - a)
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
let prefix = String(string.prefix(i + 1))
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
let suffix = String(string.suffix(i + 1))
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
```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 {
let prefix = String(string.prefix(i + 1))
prefixes.append(prefix)
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
let suffix = String(string.suffix(i + 1))
suffixes.append(suffix)
}
return suffixes
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
let substring = String(string.prefix(i + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i
for j in 0..<string.count { // immutable value 'j' was never used; consider replacing with '_' or removing it
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
let prefix = String(string.prefix(i + 1))
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
let suffix = String(string.suffix(i + 1))
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
substrings.append(substring)
}
}
return substrings
}
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring == String(substring.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring.count >= 3 && substring == String(substring.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring.count >= 3 && substring == String(substring.reversed()) && substring != string {
palindromes.append(substring)
}
}
}
return palindromes
}
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring.count >= 3 && substring == String(substring.reversed()) && substring != string && substring != String(string.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
```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 {
let prefix = String(string.prefix(i + 1))
prefixes.append(prefix)
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
let suffix = String(string.suffix(i + 1))
suffixes.append(suffix)
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings of the input string that are palindromes
// allPalindromes(string: "abccba") == ["a", "b", "c", "b", "c", "c", "b", "a", "cc", "bccb", "abcba"]
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring == String(substring.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
// Return array of all substrings of the input string that are palindromes and have a length of at least 3
// allPalindromes(string: "abccba") == ["bccb", "abcba"]
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring.count >= 3 && substring == String(substring.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
// Return array of all substrings of the input string that are palindromes and have a length of at least 3 and are not the same as the input string
// allPalindromes(string: "abccba") == ["bccb", "abcba"]
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring.count >= 3 && substring == String(substring.reversed()) && substring != string {
palindromes.append(substring)
}
}
}
return palindromes
}
// Return array of all substrings of the input string that are palindromes and have a length of at least 3 and are not the same as the input string and are not the same as the input string reversed
// allPalindromes(string: "abccba") == ["bccb", "abcba"]
func allPalindromes(string: String) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.prefix(j + 1))
if substring.count >= 3 && substring == String(substring.reversed()) && substring != string && substring != String(string.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
// Return array of all substrings of the input string that are palindromes and have a length of at least 3 and are not the same as the input string and are not the same as the input
func allPalindromes(string: String) -> [String] { // invalid redeclaration of 'allPalindromes(string:)'
func allPalindromes(string: String) -> [String] { // invalid redeclaration of 'allPalindromes(string:)'
func allPalindromes(string: String) -> [String] { // invalid redeclaration of 'allPalindromes(string:)'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
func allPermutations<T>(array: [T]) -> [[T]] {
if array.count == 0 {
return [[]]
}
var permutations = [[T]]()
for i in 0..<array.count {
let element = array[i]
let remainingElements = array.filter { $0 != element }
let remainingPermutations = allPermutations(array: remainingElements)
for permutation in remainingPermutations {
permutations.append([element] + permutation)
}
}
return permutations
}
func allCombinations<T>(array: [T]) -> [[T]] {
if array.count == 0 {
return [[]]
}
var combinations = [[T]]()
for i in 0..<array.count {
let element = array[i]
let remainingElements = array.filter { $0 != element }
let remainingCombinations = allCombinations(array: remainingElements)
for combination in remainingCombinations {
combinations.append([element] + combination)
}
}
return combinations
}
func allSubsets<T>(array: [T]) -> [[T]] {
if array.count == 0 {
return [[]]
}
var subsets = [[T]]()
for i in 0..<array.count {
let element = array[i]
let remainingElements = array.filter { $0 != element }
let remainingSubsets = allSubsets(array: remainingElements)
for subset in remainingSubsets {
subsets.append([element] + subset)
}
}
return subsets
}
```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[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all permutations of the input array
// allPermutations(array: [1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
func allPermutations<T>(array: [T]) -> [[T]] {
if array.count == 0 {
return [[]]
}
var permutations = [[T]]()
for i in 0..<array.count {
let element = array[i]
let remainingElements = array.filter { $0 != element }
let remainingPermutations = allPermutations(array: remainingElements)
for permutation in remainingPermutations {
permutations.append([element] + permutation)
}
}
return permutations
}
// Return array of all combinations of the input array
// allCombinations(array: [1, 2, 3]) == [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
func allCombinations<T>(array: [T]) -> [[T]] {
if array.count == 0 {
return [[]]
}
var combinations = [[T]]()
for i in 0..<array.count {
let element = array[i]
let remainingElements = array.filter { $0 != element }
let remainingCombinations = allCombinations(array: remainingElements)
for combination in remainingCombinations {
combinations.append([element] + combination)
}
}
return combinations
}
// Return array of all subsets of the input array
// allSubsets(array: [1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
func allSubsets<T>(array: [T]) -> [[T]] {
if array.count == 0 {
return [[]]
}
var subsets = [[T]]()
for i in 0..<array.count {
let element = array[i]
let remainingElements = array.filter { $0 != element }
let remainingSubsets = allSubsets(array: remainingElements)
for subset in remainingSubsets {
subsets.append([element] + subset)
}
}
return subsets
}
// Return array of all partitions of the input array
// allPartitions(array: [1, 2, 3]) == [[[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3]]]
func allPartitions<T>(array: [T]) -> [[[T]]] {
if array.count == 0 {
return [[]]
}
var partitions = [[[T]]]()
for i in
let remainingElements = array.filter { $0 != element } // referencing operator function '!=' on 'BinaryInteger' requires that 'T' conform to 'BinaryInteger'
let remainingPermutations = allPermutations(array: remainingElements) // generic parameter 'T' could not be inferred
let remainingElements = array.filter { $0 != element } // referencing operator function '!=' on 'BinaryInteger' requires that 'T' conform to 'BinaryInteger'
let remainingCombinations = allCombinations(array: remainingElements) // generic parameter 'T' could not be inferred
let remainingElements = array.filter { $0 != element } // referencing operator function '!=' on 'BinaryInteger' requires that 'T' conform to 'BinaryInteger'
let remainingSubsets = allSubsets(array: remainingElements) // generic parameter 'T' could not be inferred
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
let prefix = String(string.prefix(i + 1))
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
let suffix = String(string.suffix(i + 1))
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
substrings.append(substring)
}
}
return substrings
}
func allSubstrings(string: String, n: Int) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n {
substrings.append(substring)
}
}
}
return substrings
}
func allPalindromes(string: String, n: Int) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n && substring == String(substring.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
func allAnagramPalindromes(string: String, n: Int) -> [String] {
var anagramPalindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n && substring == String(substring.reversed()) && substring.sorted() == string.sorted() {
anagramPalindromes.append(substring)
}
}
}
return anagramPalindromes
}
func allPermutationPalindromes(string: String, n: Int) -> [String] {
var permutationPalindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n && substring == String(substring.reversed()) && substring.sorted() == string.sorted() && substring.permutations().contains(string) {
permutationPalindromes.append(substring)
}
}
}
return permutationPalindromes
}
```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 {
let prefix = String(string.prefix(i + 1))
prefixes.append(prefix)
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
let suffix = String(string.suffix(i + 1))
suffixes.append(suffix)
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings of the input string with length n
// allSubstrings(string: "abc", n: 2) == ["ab", "bc"]
func allSubstrings(string: String, n: Int) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n {
substrings.append(substring)
}
}
}
return substrings
}
// Return array of all substrings of the input string with length n that are palindromes
// allPalindromes(string: "abc", n: 2) == ["ab", "bc"]
func allPalindromes(string: String, n: Int) -> [String] {
var palindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n && substring == String(substring.reversed()) {
palindromes.append(substring)
}
}
}
return palindromes
}
// Return array of all substrings of the input string with length n that are palindromes and are anagrams of the input string
// allAnagramPalindromes(string: "abc", n: 2) == ["ab", "bc"]
func allAnagramPalindromes(string: String, n: Int) -> [String] {
var anagramPalindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n && substring == String(substring.reversed()) && substring.sorted() == string.sorted() {
anagramPalindromes.append(substring)
}
}
}
return anagramPalindromes
}
// Return array of all substrings of the input string with length n that are palindromes and are anagrams of the input string and are permutations of the input string
// allPermutationPalindromes(string: "abc", n: 2) == ["ab", "bc"]
func allPermutationPalindromes(string: String, n: Int) -> [String] {
var permutationPalindromes = [String]()
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string.suffix(j + 1 - i))
if substring.count == n && substring == String(substring.reversed()) && substring.sorted() == string.sorted() && substring.permutations().contains(string) {
permutationPalindromes.append(substring)
}
}
}
return permutationPalindromes
}
// Return array of all substrings of the input string with length n that are palindromes and are anagrams of the input string and are permutations of the input string and are palindromes
// allPalindromePermutationPalindromes
if substring.count == n && substring == String(substring.reversed()) && substring.sorted() == string.sorted() && substring.permutations().contains(string) { // value of type 'String' has no member 'permutations'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string.prefix(i + 1)))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string.suffix(i + 1)))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string.prefix(j + 1)))
}
}
return substrings
}
```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 + 1)))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string.suffix(i + 1)))
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string.prefix(j + 1)))
}
}
return substrings
}
// Return array of all substrings of the input string that are palindromes
// allPalindromes(string: "abccba") == ["a", "b", "c", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
```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[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy:
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
```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[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings of the input string that are palindromes
// allPalindromes(string: "abccba") == ["a", "b", "c", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "b", "a", "b", "c", "c", "
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
```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[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy:
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
func dictionaryPrefixes(string: String, dictionary: [String]) -> [String] {
var prefixes = [String]()
for prefix in allPrefixes(string: string) {
if dictionary.contains(prefix) {
prefixes.append(prefix)
}
}
return prefixes
}
func dictionarySuffixes(string: String, dictionary: [String]) -> [String] {
var suffixes = [String]()
for suffix in allSuffixes(string: string) {
if dictionary.contains(suffix) {
suffixes.append(suffix)
}
}
return suffixes
}
func dictionarySubstrings(string: String, dictionary: [String]) -> [String] {
var substrings = [String]()
for substring in allSubstrings(string: string) {
if dictionary.contains(substring) {
substrings.append(substring)
}
}
return substrings
}
```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[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all prefixes of the input string that are also in the dictionary
// dictionaryPrefixes(string: "swift", dictionary: ["swift", "strength", "swiftness"]) == ["swift"]
func dictionaryPrefixes(string: String, dictionary: [String]) -> [String] {
var prefixes = [String]()
for prefix in allPrefixes(string: string) {
if dictionary.contains(prefix) {
prefixes.append(prefix)
}
}
return prefixes
}
// Return array of all suffixes of the input string that are also in the dictionary
// dictionarySuffixes(string: "swift", dictionary: ["swift", "strength", "swiftness"]) == ["swift"]
func dictionarySuffixes(string: String, dictionary: [String]) -> [String] {
var suffixes = [String]()
for suffix in allSuffixes(string: string) {
if dictionary.contains(suffix) {
suffixes.append(suffix)
}
}
return suffixes
}
// Return array of all substrings of the input string that are also in the dictionary
// dictionarySubstrings(string: "swift", dictionary: ["swift", "strength", "swiftness"]) == ["swift"]
func dictionarySubstrings(string: String, dictionary: [String]) -> [String] {
var substrings = [String]()
for substring in allSubstrings(string: string) {
if dictionary.contains(substring) {
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings of the input string that are also in the dictionary
// dictionarySubstrings(string: "swift", dictionary: ["swift", "strength", "swiftness"]) == ["swift"]
func dictionarySubstrings(string: String, dictionary: [String]) -> [String] {
var substrings = [String]()
for substring in allSubstrings(string: string) {
if dictionary.contains(substring) {
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings of the input string that are also in the dictionary
// dictionarySubstrings(string: "swift", dictionary: ["swift", "strength", "swiftness"]) == ["swift"]
func dictionarySubstrings(string: String, dictionary: [String]) -> [String] {
var substrings = [String]()
for substring in allSubstrings(string: string) {
if dictionary.contains(substring) {
substrings.append(substring)
}
}
return substrings
}
// Return array of all substrings of the input string that are also in the dictionary
// dictionarySubstrings(string: "swift", dictionary: ["swift", "strength", "swiftness"]) == ["swift"]
func dictionarySubstrings(string: String, dictionary: [String]) -> [String] {
var substrings = [String]()
for substring in allSubstrings(string: string) {
if dictionary.contains(substring) {
substrings.append(substring)
}
}
return substrings
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(String(string[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
func allSubstringsOfLength(string: String, length: Int) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
}
return substrings
}
func allSubstringsOfLengthWithoutRepeats(string: String, length: Int) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
}
return substrings
}
func allSubstringsWithoutRepeats(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
}
return substrings
}
```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[string.startIndex..<string.index(string.startIndex, offsetBy: i + 1)]))
}
return prefixes
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.endIndex]))
}
return suffixes
}
// Return array of all substrings of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
return substrings
}
// Return array of all substrings of the input string with length n
// allSubstringsOfLength(string: "abc", length: 2) == ["ab", "bc"]
func allSubstringsOfLength(string: String, length: Int) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
}
return substrings
}
// Return array of all substrings of the input string with length n and no repeated characters
// allSubstringsOfLength(string: "abc", length: 2) == ["ab", "bc"]
func allSubstringsOfLengthWithoutRepeats(string: String, length: Int) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
}
return substrings
}
// Return array of all substrings of the input string with no repeated characters
// allSubstringsWithoutRepeats(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstringsWithoutRepeats(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: j + 1)]))
}
}
}
return substrings
}
// Return array of all substrings of the input string with no repeated characters and no repeated characters
// allSubstringsWithoutRepeats(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstringsWithoutRepeats(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in i..<string.count {
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) ==
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length { // referencing operator function '-' on 'Strideable' requires that 'String.Index' conform to '_Pointer'
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length { // referencing operator function '-' on 'Strideable' requires that 'String.Index' conform to '_Pointer'
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length { // cannot find 'length' in scope
if string.index(string.startIndex, offsetBy: j + 1) - string.index(string.startIndex, offsetBy: i) == length { // referencing operator function '-' on 'FloatingPoint' requires that 'String.Index' conform to 'FloatingPoint'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
let string = string.lowercased()
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let string = string.lowercased()
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string.lowercased() {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string.lowercased() {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character.lowercased().first!)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character.lowercased().first!)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var count = 0
var distinct = [Character: Int]()
for char in string {
let char = char.lowercased()
if distinct[char] == nil {
distinct[char] = 1
count += 1
}
}
return count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var distinct = [Character: Int]()
for char in string {
let char = char.lowercased()
if distinct[char] == nil {
distinct[char] = 1
count += 1
}
}
return count
}
```
if distinct[char] == nil { // cannot convert value of type 'String' to expected argument type 'Character'
distinct[char] = 1 // cannot convert value of type 'String' to expected argument type 'Character'
func countDistinctCharacters(string: String) -> Int {
let string = string.lowercased()
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let string = string.lowercased()
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string.lowercased() {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string.lowercased() {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var count = 0
var charSet = Set<Character>()
for char in string.lowercased() {
if !charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var charSet = Set<Character>()
for char in string.lowercased() {
if !charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
```
func countDistinctCharacters(string: String) -> Int {
let lowercasedString = string.lowercased()
var distinctCharacters = Set<Character>()
for character in lowercasedString {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let lowercasedString = string.lowercased()
var distinctCharacters = Set<Character>()
for character in lowercasedString {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func countDistinctCharacters(string: String) -> Int {
var charSet = Set<Character>()
for char in string.lowercased() {
charSet.insert(char)
}
return charSet.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 charSet = Set<Character>()
for char in string.lowercased() {
charSet.insert(char)
}
return charSet.count
}
```
func countDistinctCharacters(string: String) -> Int {
let string = string.lowercased()
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let string = string.lowercased()
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
for char in musicString {
switch char {
case "o":
result.append(4)
case "|":
result.append(2)
case ".":
result.append(1)
default:
break
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
for char in musicString {
switch char {
case "o":
result.append(4)
case "|":
result.append(2)
case ".":
result.append(1)
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var current: Int = 0
for char in musicString {
switch char {
case "o":
current = 4
case "|":
current = 2
case ".":
current = 1
default:
break
}
result.append(current)
}
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 current: Int = 0
for char in musicString {
switch char {
case "o":
current = 4
case "|":
current = 2
case ".":
current = 1
default:
break
}
result.append(current)
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var beats = [Int]()
for note in musicString.split(separator: " ") {
switch note {
case "o":
beats.append(4)
case "o|":
beats.append(2)
case ".|":
beats.append(1)
default:
break
}
}
return beats
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var beats = [Int]()
for note in musicString.split(separator: " ") {
switch note {
case "o":
beats.append(4)
case "o|":
beats.append(2)
case ".|":
beats.append(1)
default:
break
}
}
return beats
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
result.append(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]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
result.append(0)
}
}
return result
}
```
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var current: Int = 0
for char in musicString {
switch char {
case "o":
current = 4
case "|":
current = 2
case ".":
current = 1
default:
break
}
result.append(current)
}
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 current: Int = 0
for char in musicString {
switch char {
case "o":
current = 4
case "|":
current = 2
case ".":
current = 1
default:
break
}
result.append(current)
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var current: Int = 0
for char in musicString {
switch char {
case "o":
current = 4
case "|":
current = 2
case ".":
current = 1
default:
break
}
result.append(current)
}
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 current: Int = 0
for char in musicString {
switch char {
case "o":
current = 4
case "|":
current = 2
case ".":
current = 1
default:
break
}
result.append(current)
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var notes = [Int]()
var currentNote = ""
for char in musicString {
if char == "o" || char == "|" || char == "." {
currentNote += String(char)
} else if char == " " {
if currentNote == "o" {
notes.append(4)
} else if currentNote == "o|" {
notes.append(2)
} else if currentNote == ".|" {
notes.append(1)
}
currentNote = ""
}
}
return notes
}
```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 notes = [Int]()
var currentNote = ""
for char in musicString {
if char == "o" || char == "|" || char == "." {
currentNote += String(char)
} else if char == " " {
if currentNote == "o" {
notes.append(4)
} else if currentNote == "o|" {
notes.append(2)
} else if currentNote == ".|" {
notes.append(1)
}
currentNote = ""
}
}
return notes
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var notes = [Int]()
for note in musicString.split(separator: " ") {
switch note {
case "o":
notes.append(4)
case "o|":
notes.append(2)
case ".|":
notes.append(1)
default:
notes.append(0)
}
}
return notes
}
```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 notes = [Int]()
for note in musicString.split(separator: " ") {
switch note {
case "o":
notes.append(4)
case "o|":
notes.append(2)
case ".|":
notes.append(1)
default:
notes.append(0)
}
}
return notes
}
```
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
let notes = musicString.split(separator: " ")
for note in notes {
switch note {
case "o":
result.append(4)
case "o|":
result.append(2)
case ".|":
result.append(1)
default:
break
}
}
return result
}
```
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index < string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex) {
count += 1
index = range.upperBound
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while let range = string.range(of: substring, options: [], range: index..<string.endIndex) {
count += 1
index = range.upperBound
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: index..<string.endIndex) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<index) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<index) {
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 let range = string.range(of: substring, range: string.index(index, offsetBy: substring.count)..<string.endIndex) {
count += 1
index = range.lowerBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, range: string.index(index, offsetBy: substring.count)..<string.endIndex) {
count += 1
index = range.lowerBound
} 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 let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = string.startIndex
while index != string.endIndex {
if let range = string.range(of: substring, options: .caseInsensitive, range: string.startIndex..<string.endIndex, locale: nil) {
count += 1
index = range.upperBound
} else {
break
}
}
return count
}
```
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
var numbersArray = numbers.components(separatedBy: " ")
numbersArray.sort()
return numbersArray.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 {
var numbersArray = numbers.components(separatedBy: " ")
numbersArray.sort()
return numbersArray.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
var numbersArraySorted = numbersArray.sorted()
return numbersArraySorted.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
var numbersArraySorted = numbersArray.sorted()
return numbersArraySorted.joined(separator: " ")
}
```
var numbersArraySorted = numbersArray.sorted() // variable 'numbersArraySorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
var numbersArraySorted = numbersArray.sorted()
return numbersArraySorted.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
var numbersArraySorted = numbersArray.sorted()
return numbersArraySorted.joined(separator: " ")
}
```
var numbersArraySorted = numbersArray.sorted() // variable 'numbersArraySorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
var numbers = numbers.components(separatedBy: " ")
numbers.sort()
return numbers.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 {
var numbers = numbers.components(separatedBy: " ")
numbers.sort()
return numbers.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted()
let numbersArraySortedString = numbersArraySorted.joined(separator: " ")
return numbersArraySortedString
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted(by: { $0 < $1 })
return numbersArraySorted.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbersArray = numbers.components(separatedBy: " ")
let numbersArraySorted = numbersArray.sorted(by: { $0 < $1 })
return numbersArraySorted.joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
var numbersArray = numbers.components(separatedBy: " ")
numbersArray.sort()
return numbersArray.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 {
var numbersArray = numbers.components(separatedBy: " ")
numbersArray.sort()
return numbersArray.joined(separator: " ")
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted.first!
let last = sorted.last!
let middle = sorted[sorted.count / 2]
let firstMiddle = abs(first - middle)
let lastMiddle = abs(last - middle)
if firstMiddle < lastMiddle {
return (first, middle)
} else {
return (last, middle)
}
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted.first!
let last = sorted.last!
let middle = sorted[sorted.count / 2]
let firstMiddle = abs(first - middle)
let lastMiddle = abs(last - middle)
if firstMiddle < lastMiddle {
return (first, middle)
} else {
return (last, middle)
}
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let count = sorted.count
let mid = count / 2
let first = sorted[mid]
let second = sorted[mid + 1]
return (first, second)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let count = sorted.count
let mid = count / 2
let first = sorted[mid]
let second = sorted[mid + 1]
return (first, second)
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted.first!
let last = sorted.last!
let middle = sorted.count / 2
let second = sorted[middle]
let third = sorted[middle - 1]
let firstSecond = abs(first - second)
let firstThird = abs(first - third)
let secondThird = abs(second - third)
if firstSecond < firstThird && firstSecond < secondThird {
return (first, second)
} else if firstThird < firstSecond && firstThird < secondThird {
return (first, third)
} else {
return (second, third)
}
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted.first!
let last = sorted.last!
let middle = sorted.count / 2
let second = sorted[middle]
let third = sorted[middle - 1]
let firstSecond = abs(first - second)
let firstThird = abs(first - third)
let secondThird = abs(second - third)
if firstSecond < firstThird && firstSecond < secondThird {
return (first, second)
} else if firstThird < firstSecond && firstThird < secondThird {
return (first, third)
} else {
return (second, third)
}
}
```
let last = sorted.last! // initialization of immutable value 'last' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = numbers[0] - numbers[1]
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = numbers[i] - numbers[j]
if abs(distance) < abs(closestDistance) {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = numbers[0] - numbers[1]
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = numbers[i] - numbers[j]
if abs(distance) < abs(closestDistance) {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = numbers[0] - numbers[1]
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = numbers[i] - numbers[j]
if abs(distance) < abs(closestDistance) {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = numbers[0] - numbers[1]
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = numbers[i] - numbers[j]
if abs(distance) < abs(closestDistance) {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let count = sorted.count
var closest = (sorted[0], sorted[1])
var closestDistance = sorted[1] - sorted[0]
for i in 0..<count-1 {
let distance = sorted[i+1] - sorted[i]
if distance < closestDistance {
closest = (sorted[i], sorted[i+1])
closestDistance = distance
}
}
return closest
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let count = sorted.count
var closest = (sorted[0], sorted[1])
var closestDistance = sorted[1] - sorted[0]
for i in 0..<count-1 {
let distance = sorted[i+1] - sorted[i]
if distance < closestDistance {
closest = (sorted[i], sorted[i+1])
closestDistance = distance
}
}
return closest
}
```
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let first = sortedNumbers.first!
let last = sortedNumbers.last!
let middle = sortedNumbers.count / 2
let middleValue = sortedNumbers[middle]
let middleValueBefore = sortedNumbers[middle - 1]
let middleValueAfter = sortedNumbers[middle + 1]
let middleValueBeforeDistance = abs(middleValue - middleValueBefore)
let middleValueAfterDistance = abs(middleValue - middleValueAfter)
let middleValueDistance = abs(middleValue - middleValueBefore) < abs(middleValue - middleValueAfter) ? middleValueBefore : middleValueAfter
let closestElements = (middleValueBeforeDistance < middleValueAfterDistance ? (middleValueBefore, middleValueDistance) : (middleValueDistance, middleValueAfter))
return (closestElements.0, closestElements.1)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let first = sortedNumbers.first!
let last = sortedNumbers.last!
let middle = sortedNumbers.count / 2
let middleValue = sortedNumbers[middle]
let middleValueBefore = sortedNumbers[middle - 1]
let middleValueAfter = sortedNumbers[middle + 1]
let middleValueBeforeDistance = abs(middleValue - middleValueBefore)
let middleValueAfterDistance = abs(middleValue - middleValueAfter)
let middleValueDistance = abs(middleValue - middleValueBefore) < abs(middleValue - middleValueAfter) ? middleValueBefore : middleValueAfter
let closestElements = (middleValueBeforeDistance < middleValueAfterDistance ? (middleValueBefore, middleValueDistance) : (middleValueDistance, middleValueAfter))
return (closestElements.0, closestElements.1)
}
```
let first = sortedNumbers.first! // initialization of immutable value 'first' was never used; consider replacing with assignment to '_' or removing it
let last = sortedNumbers.last! // initialization of immutable value 'last' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = numbers[0] - numbers[1]
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = numbers[i] - numbers[j]
if abs(distance) < abs(closestDistance) {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = numbers[0] - numbers[1]
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = numbers[i] - numbers[j]
if abs(distance) < abs(closestDistance) {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = abs(closest.0 - closest.1)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < closestDistance {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var closest = (numbers[0], numbers[1])
var closestDistance = abs(closest.0 - closest.1)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let distance = abs(numbers[i] - numbers[j])
if distance < closestDistance {
closest = (numbers[i], numbers[j])
closestDistance = distance
}
}
}
return closest
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted.first!
let last = sorted.last!
let middle = sorted.count / 2
let firstHalf = sorted[0..<middle]
let secondHalf = sorted[middle..<sorted.count]
let firstHalfSorted = firstHalf.sorted(by: { abs($0 - first) < abs($0 - last) })
let secondHalfSorted = secondHalf.sorted(by: { abs($0 - first) < abs($0 - last) })
let firstHalfClosest = firstHalfSorted.first!
let secondHalfClosest = secondHalfSorted.first!
return (firstHalfClosest, secondHalfClosest)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted.first!
let last = sorted.last!
let middle = sorted.count / 2
let firstHalf = sorted[0..<middle]
let secondHalf = sorted[middle..<sorted.count]
let firstHalfSorted = firstHalf.sorted(by: { abs($0 - first) < abs($0 - last) })
let secondHalfSorted = secondHalf.sorted(by: { abs($0 - first) < abs($0 - last) })
let firstHalfClosest = firstHalfSorted.first!
let secondHalfClosest = secondHalfSorted.first!
return (firstHalfClosest, secondHalfClosest)
}
```
let firstHalfSorted = firstHalf.sorted(by: { abs($0 - first) < abs($0 - last) }) // contextual closure type '(Double, Double) throws -> Bool' expects 2 arguments, but 1 was used in closure body
let secondHalfSorted = secondHalf.sorted(by: { abs($0 - first) < abs($0 - last) }) // contextual closure type '(Double, Double) throws -> Bool' expects 2 arguments, but 1 was used in closure body
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 }
}
// 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 }
}
// 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 }
}
// 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 }
}
// 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 }
}
// 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 }
}
// 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()!
let range = max - min
return numbers.map { ($0 - min) / range }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { ($0 - min) / range }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
guard numbers.count > 1 else {
return numbers
}
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map {
($0 - min) / range
}
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0
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()!
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()!
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()!
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()!
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()!
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()!
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 filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
func filterIntegers(values: [AnyHashable]) -> [Int] {
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 strlen(string: String) -> Int {
return string.characters.count
}
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string.characters {
if c == character {
count += 1
}
}
return count
}
func strremove(string: String, character: Character) -> String {
var result = ""
for c in string.characters {
if c != character {
result += String(c)
}
}
return result
}
func strreplace(string: String, oldCharacter: Character, newCharacter: Character) -> String {
var result = ""
for c in string.characters {
if c == oldCharacter {
result += String(newCharacter)
} else {
result += String(c)
}
}
return result
}
func strreplacestring(string: String, oldCharacter: Character, newString: String) -> String {
var result = ""
for c in string.characters {
if c == oldCharacter {
result += newString
} else {
result += String(c)
}
}
return result
}
func strreplacestrings(string: String, oldString: String, newString: String) -> String {
var result = ""
var index = 0
while index < string.characters.count {
let substring = string.substringWithRange(Range<String.Index>(start: string.startIndex.advancedBy(index), end: string.startIndex.advancedBy(index + oldString.characters.count)))
if substring == oldString {
result += newString
index += oldString.characters.count
} else {
result += String(string.characters[string.startIndex.advancedBy(index)])
index += 1
}
}
return result
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
// Return number of occurrences of a given character in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string.characters {
if c == character {
count += 1
}
}
return count
}
// Return a string with all occurrences of a given character removed
// strremove(string: "abc", character: "a") == "bc"
// strremove(string: "abc", character: "b") == "ac"
// strremove(string: "abc", character: "c") == "ab"
// strremove(string: "abc", character: "d") == "abc"
func strremove(string: String, character: Character) -> String {
var result = ""
for c in string.characters {
if c != character {
result += String(c)
}
}
return result
}
// Return a string with all occurrences of a given character replaced with a new character
// strreplace(string: "abc", oldCharacter: "a", newCharacter: "d") == "dbc"
// strreplace(string: "abc", oldCharacter: "b", newCharacter: "d") == "adc"
// strreplace(string: "abc", oldCharacter: "c", newCharacter: "d") == "abd"
// strreplace(string: "abc", oldCharacter: "d", newCharacter: "d") == "abc"
func strreplace(string: String, oldCharacter: Character, newCharacter: Character) -> String {
var result = ""
for c in string.characters {
if c == oldCharacter {
result += String(newCharacter)
} else {
result += String(c)
}
}
return result
}
// Return a string with all occurrences of a given character replaced with a new string
// strreplacestring(string: "abc", oldCharacter: "a", newString: "d") == "dbc"
// strreplacestring(string: "abc", oldCharacter: "b", newString: "d") == "adc"
// strreplacestring(string: "abc", oldCharacter: "c", newString: "d") == "abd"
// strreplacestring(string: "abc", oldCharacter: "d", newString: "d") == "abc"
func strreplacestring(string: String, oldCharacter: Character, newString: String) -> String {
var result = ""
for c in string.characters {
if c == oldCharacter {
result += newString
} else {
result += String(c)
}
}
return result
}
// Return a string with all occurrences of a given string replaced with a new string
// strreplacestrings(string: "abc", oldString: "a", newString: "d") == "dbc"
// strreplacestrings(string: "abc", oldString: "b", newString: "d") == "adc"
// strreplacestrings(string: "abc", oldString: "c", newString: "d") == "abd"
// strreplacestrings(string: "abc", oldString: "d", newString: "d") == "abc"
func strreplacestrings(string: String, oldString: String, newString: String) -> String {
var result = ""
var index = 0
while index < string.characters.count {
let substring = string.substringWithRange(Range<String.Index>(start: string.startIndex.advancedBy(index), end: string.startIndex.advancedBy(index + oldString.characters.count)))
if substring == oldString {
result += newString
index += oldString.characters.count
} else {
result += String(string.characters[string.startIndex.advancedBy(index)])
index += 1
}
}
return result
}
// Return a string with all occurrences of a given string replaced with a new string
// strreplacestrings
return string.characters.count // 'characters' is unavailable: Please use String directly
for c in string.characters { // 'characters' is unavailable: Please use String directly
for c in string.characters { // 'characters' is unavailable: Please use String directly
for c in string.characters { // 'characters' is unavailable: Please use String directly
for c in string.characters { // 'characters' is unavailable: Please use String directly
while index < string.characters.count { // 'characters' is unavailable: Please use String directly
let substring = string.substringWithRange(Range<String.Index>(start: string.startIndex.advancedBy(index), end: string.startIndex.advancedBy(index + oldString.characters.count))) // incorrect argument labels in call (have 'start:end:', expected '_:in:')
let substring = string.substringWithRange(Range<String.Index>(start: string.startIndex.advancedBy(index), end: string.startIndex.advancedBy(index + oldString.characters.count))) // value of type 'String.Index' has no member 'advancedBy'
let substring = string.substringWithRange(Range<String.Index>(start: string.startIndex.advancedBy(index), end: string.startIndex.advancedBy(index + oldString.characters.count))) // value of type 'String' has no member 'substringWithRange'
let substring = string.substringWithRange(Range<String.Index>(start: string.startIndex.advancedBy(index), end: string.startIndex.advancedBy(index + oldString.characters.count))) // value of type 'String.Index' has no member 'advancedBy'
index += oldString.characters.count // 'characters' is unavailable: Please use String directly
result += String(string.characters[string.startIndex.advancedBy(index)]) // value of type 'String.Index' has no member 'advancedBy'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
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
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count += 1
if count == n {
break
}
}
return count
}
// Return length of given string
// strnlen(string: "", n: 0) == 0
// strnlen(string: "abc", n: 3) == 3
func strnlen(string: String, n: Int) -> Int {
var count = 0
for _ in string {
count
func strlen(string: String) -> Int {
return string.characters.count
}
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return count
}
func strchar(string: String, char: Character) -> Int {
var count = 0
for c in string.characters {
if c == char {
count += 1
}
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.characters.count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: Character) -> Int {
var count = 0
for c in string.characters {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strchar(string: "abc", char: "a") == 1
// strchar(string: "abc", char: "b") == 1
// strchar(string: "abc", char: "c") == 1
// strchar(string: "abc", char: "d") == 0
func strchar(string: String, char: String) -> Int {
var count = 0
for c in string.characters {
if String(c) == char {
count += 1
}
}
return string.characters.count // 'characters' is unavailable: Please use String directly
for c in string.characters { // 'characters' is unavailable: Please use String directly
for c in string.characters { // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strReplace(string: String, old: String, new: String) -> String {
var result = ""
for char in string {
if String(char) == old {
result += new
} else {
result += String(char)
}
}
return result
}
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
```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 a new string with all occurrences of a character replaced with another
// strReplace(string: "abc", old: "a", new: "z") == "zbc"
func strReplace(string: String, old: String, new: String) -> String {
var result = ""
for char in string {
if String(char) == old {
result += new
} else {
result += String(char)
}
}
return result
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a character removed
// strRemove(string: "abc", old: "a") == "bc"
func strRemove(string: String, old: String) -> String {
return strReplace(string: string, old: old, new: "")
}
// Return a new string with all occurrences of a
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
func strcount(string: String, substring: String) -> Int {
var count = 0
var i = 0
while i < strlen(string: string) {
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) {
count += 1
i += strlen(string: substring)
} else {
i += 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
}
// Return the number of times a character appears in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return the number of times a substring appears in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
var i = 0
while i < strlen(string: string) {
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) {
count += 1
i += strlen(string: substring)
} else {
i += 1
}
}
return count
}
// Return the number of times a substring appears in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
var i = 0
while i < strlen(string: string) {
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) {
count += 1
i += strlen(string: substring)
} else {
i += 1
}
}
return count
}
// Return the number of times a substring appears in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
var i = 0
while i < strlen(string: string) {
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) {
count += 1
i += strlen(string: substring)
} else {
i += 1
}
}
return count
}
// Return the number of times a substring appears in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
var i = 0
while i < strlen(string: string) {
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) {
count += 1
i += strlen(string: substring)
} else {
i += 1
}
}
return count
}
// Return the number of times a substring appears in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) { // value of type 'String.Index' has no member 'advancedBy'
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) { // extra argument 'range' in call
if string.hasPrefix(substring, range: Range(start: string.startIndex.advancedBy(i), end: string.endIndex)) { // extra argument 'end' in call
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring {
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
}
// Return number of occurrences of a given character in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: Range(NSMakeRange
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring { // cannot convert value of type 'Range<Int>' to expected argument type 'Range<String.Index>'
if string.substring(with: Range(NSMakeRange(i, strlen(string: substring)))) == substring { // value of optional type 'Range<Int>?' must be unwrapped to a value of type 'Range<Int>'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
var found = true
for j in 0..<strlen(string: substring) {
if string[string.index(string.startIndex, offsetBy: i + j)] != substring[substring.index(substring.startIndex, offsetBy: j)] {
found = false
break
}
}
if found {
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
}
// Return the number of occurrences of a given character in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
var found = true
for j in 0..<strlen(string: substring) {
if string[string.index(string.startIndex, offsetBy: i + j)] != substring[substring.index(substring.startIndex, offsetBy: j)] {
found = false
break
}
}
if found {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
var found = true
for j in 0..<strlen(string: substring) {
if string[string.index(string.startIndex, offsetBy: i + j)] != substring[substring.index(substring.startIndex, offsetBy: j)] {
found = false
break
}
}
if found {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
var found = true
for j in 0..<strlen(string: substring) {
if string[string.index(string.startIndex, offsetBy: i + j)] != substring[substring.index(substring.startIndex, offsetBy: j)] {
found = false
break
}
}
if found {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
var found = true
for j in 0..<strlen(string: substring) {
if string[string.index(string.startIndex
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcount(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
func strreplace(string: String, old: Character, new: Character) -> String {
var result = ""
for c in string {
if c == old {
result += String(new)
} else {
result += String(c)
}
}
return result
}
func strremove(string: String, char: Character) -> String {
var result = ""
for c in string {
if c != char {
result += String(c)
}
}
return result
}
```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 number of occurrences of a given character in a string
// strcount(string: "abc", char: "a") == 1
// strcount(string: "abc", char: "b") == 1
// strcount(string: "abc", char: "c") == 1
// strcount(string: "abc", char: "d") == 0
func strcount(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return a new string with all occurrences of a given character replaced with another character
// strreplace(string: "abc", old: "a", new: "d") == "dbc"
// strreplace(string: "abc", old: "b", new: "d") == "adc"
// strreplace(string: "abc", old: "c", new: "d") == "abd"
// strreplace(string: "abc", old: "d", new: "d") == "abc"
func strreplace(string: String, old: Character, new: Character) -> String {
var result = ""
for c in string {
if c == old {
result += String(new)
} else {
result += String(c)
}
}
return result
}
// Return a new string with all occurrences of a given character removed
// strremove(string: "abc", char: "a") == "bc"
// strremove(string: "abc", char: "b") == "ac"
// strremove(string: "abc", char: "c") == "ab"
// strremove(string: "abc", char: "d") == "abc"
func strremove(string: String, char: Character) -> String {
var result = ""
for c in string {
if c != char {
result += String(c)
}
}
return result
}
// Return a new string with all occurrences of a given character removed
// strremove(string: "abc", char: "a") == "bc"
// strremove(string: "abc", char: "b") == "ac"
// strremove(string: "abc", char: "c") == "ab"
// strremove(string: "abc", char: "d") == "abc"
func strremove(string: String, char: Character) -> String {
var result = ""
for c in string {
if c != char {
result += String(c)
}
}
return result
}
// Return a new string with all occurrences of a given character removed
// strremove(string: "abc", char: "a") == "bc"
// strremove(string: "abc", char: "b") == "ac"
// strremove(string: "abc", char: "c") == "ab"
// strremove(string: "abc", char: "d") == "abc"
func strremove(string: String, char: Character) -> String {
var result = ""
for c in string {
if c != char {
result += String(c)
}
}
return result
}
// Return a new string with all occurrences of a given character removed
// strremove(string: "abc", char: "a") == "bc"
// strremove(string: "abc", char: "b") == "ac"
// strremove(string: "abc", char: "c") == "ab"
// strremove(string: "abc", char: "d") == "abc"
func strremove(string: String, char: Character) -> String {
var result = ""
for c in string {
if c != char {
result += String(c)
}
}
return result
}
// Return a new string with all occurrences of a given character removed
// strremove(string: "abc", char: "a") == "bc"
// strremove(string: "abc", char: "b") == "ac"
// strremove(string: "abc", char: "c") == "ab"
// strremove(string: "abc", char: "d
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
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
}
// Return number of occurrences of given character in given string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return number of occurrences of given substring in given string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of given substring in given string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of given substring in given string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of given substring in given string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
count += 1
}
}
return count
}
// Return number of occurrences of given substring in given string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc",
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring { // 'substring(with:)' is deprecated: Please use String slicing subscript.
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
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
}
// Return the number of occurrences of a given character in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring {
count += 1
}
}
return count
}
// Return the number of occurrences of a given character in a string
// strcount(string: "abc", character: "a") == 1
// strcount(string: "abc", character: "b") == 1
// strcount(string: "abc", character: "c") == 1
// strcount(string: "abc", character: "d") == 0
func strcount(string: String, character: Character) -> Int {
var count = 0
for c in string {
if c == character {
count += 1
}
}
return count
}
// Return the number of occurrences of a given substring in a string
// strcount(string: "abc", substring: "a") == 1
// strcount(string: "abc", substring: "b") == 1
// strcount(string: "abc", substring: "c") == 1
// strcount(string: "abc", substring: "d") == 0
func strcount(string: String, substring: String) -> Int {
var count = 0
for i in 0..<strlen(string: string) - strlen(string: substring) + 1 {
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring
if string.substring(with: string.index(string.startIndex, offsetBy: i)..<string.index(string.startIndex, offsetBy: i + strlen(string: substring))) == substring { // 'substring(with:)' is deprecated: Please use String slicing subscript.
func largestDivisor(n: Int) -> Int {
for i in stride(from: n, to: 1, by: -1) {
if n % i == 0 {
return i
}
}
return 0
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in stride(from: n, to: 1, by: -1) {
if n % i == 0 {
return i
}
}
return 0
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var i = n - 1
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 0
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n - 1
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 0
}
// largestDivisor(n: 15)
// largestDivisor(n: 12)
// largestDivisor(n: 100)
// largestDivisor(n: 99)
// largestDivisor(n: 1000000000)
// largestDivisor(n: 1000000000000000000)
// largestDivisor(n: 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
func largestDivisor(n: Int) -> Int {
var divisor = 0
for i in 1..<n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var divisor = 0
for i in 1..<n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```
func largestDivisor(n: Int) -> Int {
for i in stride(from: n, to: 0, by: -1) {
if n % i == 0 {
return i
}
}
return 0
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in stride(from: n, to: 0, by: -1) {
if n % i == 0 {
return i
}
}
return 0
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var i = n - 1
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 0
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n - 1
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 0
}
```
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
// largestDivisor(n: 15)
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
for i in stride(from: n, to: 0, by: -1) {
if n % i == 0 {
return i
}
}
return 0
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in stride(from: n, to: 0, by: -1) {
if n % i == 0 {
return i
}
}
return 0
}
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1..<n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var divisor = 1
for i in 1..<n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
// largestDivisor(n: 15)
```
func largestDivisor(n: Int) -> Int {
var divisor = 0
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var divisor = 0
for i in 1...n {
if n % i == 0 {
divisor = i
}
}
return divisor
}
```
// XCTAssertTrue failed
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while number > 1 {
while number % factor == 0 {
factors.append(factor)
number /= factor
}
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 {
while number % factor == 0 {
factors.append(factor)
number /= factor
}
factor += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while number > 1 {
while number % factor == 0 {
factors.append(factor)
number /= factor
}
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 {
while number % factor == 0 {
factors.append(factor)
number /= factor
}
factor += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var factor = 2
while number > 1 {
while number % factor == 0 {
factors.append(factor)
number /= factor
}
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 {
while number % factor == 0 {
factors.append(factor)
number /= factor
}
factor += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
factors.append(divisor)
number /= divisor
}
divisor += 1
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var divisor = 2
while number > 1 {
while number % divisor == 0 {
factors.append(divisor)
number /= divisor
}
divisor += 1
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var number = n
var i = 2
while i <= number {
if number % i == 0 {
factors.append(i)
number /= i
} else {
i += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
var number = n
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 i = 2
var number = n
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]()
var seen = [Int: Bool]()
for number in numbers {
if !seen[number] {
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] {
result.append(number)
seen[number] = true
}
}
return result
}
```
if !seen[number] { // value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for number in numbers {
if !set.contains(number) {
set.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 set = Set<Int>()
for number in numbers {
if !set.contains(number) {
set.insert(number)
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for number in numbers {
if seen[number] == nil {
seen[number] = true
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 = [Int: Bool]()
for number in numbers {
if seen[number] == nil {
seen[number] = true
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for number in numbers {
if !set.contains(number) {
set.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 set = Set<Int>()
for number in numbers {
if !set.contains(number) {
set.insert(number)
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for number in numbers {
if seen[number] == nil {
seen[number] = true
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 = [Int: Bool]()
for number in numbers {
if seen[number] == nil {
seen[number] = true
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var unique = [Int]()
for number in numbers {
if !unique.contains(number) {
unique.append(number)
}
}
return unique
}
```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 unique = [Int]()
for number in numbers {
if !unique.contains(number) {
unique.append(number)
}
}
return unique
}
```
// 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 unique = [Int]()
for number in numbers {
if !unique.contains(number) {
unique.append(number)
}
}
return unique
}
```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 unique = [Int]()
for number in numbers {
if !unique.contains(number) {
unique.append(number)
}
}
return unique
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int: Bool]()
for number in numbers {
if !seen.keys.contains(number) {
seen[number] = true
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 = [Int: Bool]()
for number in numbers {
if !seen.keys.contains(number) {
seen[number] = true
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```
func flipCase(string: String) -> String {
var newString = ""
for character in string {
if character.isLowercase {
newString.append(character.uppercased())
} else {
newString.append(character.lowercased())
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var newString = ""
for character in string {
if character.isLowercase {
newString.append(character.uppercased())
} else {
newString.append(character.lowercased())
}
}
return newString
}
// flipCase(string: "Hello")
// flipCase(string: "hELLO")
// flipCase(string: "Hello, World!")
// flipCase(string: "12345")
// flipCase(string: "12345.67890")
// flipCase(string: "12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890")
// flipCase(string: "12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 12345.67890, 1
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
```
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isUppercase {
newString += String(char).lowercased()
} else if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char)
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isUppercase {
newString += String(char).lowercased()
} else if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char)
}
}
return newString
}
```
func flipCase(string: String) -> String {
var newString = ""
for character in string {
if character.isUppercase {
newString.append(character.lowercased())
} else if character.isLowercase {
newString.append(character.uppercased())
} else {
newString.append(character)
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var newString = ""
for character in string {
if character.isUppercase {
newString.append(character.lowercased())
} else if character.isLowercase {
newString.append(character.uppercased())
} else {
newString.append(character)
}
}
return newString
}
// flipCase(string: "Hello")
```
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let charArray = Array(string)
var newString = ""
for char in charArray {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var newString = ""
for char in string {
if char.isLowercase {
newString += String(char).uppercased()
} else {
newString += String(char).lowercased()
}
}
return newString
}
```
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(char).lowercased()
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(char).lowercased()
}
}
return result
}
```
func 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
}
```
```swift
// Con
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
// 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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
var result = ""
for string in strings {
result += string
}
return result
}
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
// 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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
var result = ""
for string in strings {
result += string
}
return result
}
func concatenate(strings: [String]) -> String {
var result = ""
for s in strings {
result += s
}
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 s in strings {
result += s
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for s in strings {
result += s
}
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 s in strings {
result += s
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
// 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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
var result = ""
for string in strings {
result += string
}
return result
}
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
// 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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
var result = ""
for string in strings {
result += string
}
return result
}
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.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] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func filterBySuffix(strings: [String], suffix: String) -> [String] {
return strings.filter { $0.hasSuffix(suffix) }
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
// Filter an input array of strings only for ones that end with a given suffix.
// filterBySuffix(strings: [] as [String], suffix: "a") == [] as [String]
// filterBySuffix(strings: ["abc", "bcd", "cde", "array"], suffix: "a") == ["array"]
func filterBySuffix(strings: [String], suffix: String) -> [String] {
return strings.filter { $0.hasSuffix(suffix) }
}
// Filter an input array of strings only for ones that contain a given substring.
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["abc", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
//
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) }
}
func filterBySuffix(strings: [String], suffix: String) -> [String] {
return strings.filter { $0.hasSuffix(suffix) }
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
// Filter an input array of strings only for ones that end with a given suffix.
// filterBySuffix(strings: [] as [String], suffix: "a") == [] as [String]
// filterBySuffix(strings: ["abc", "bcd", "cde", "array"], suffix: "y") == ["array"]
func filterBySuffix(strings: [String], suffix: String) -> [String] {
return strings.filter { $0.hasSuffix(suffix) }
}
// Filter an input array of strings only for ones that contain a given substring.
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["abc", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
// filterByString(strings: ["abc", "bcd", "cde", "array"], string: "array") == ["array"]
func filterByString(strings: [String], string: String) -> [String] {
return strings.filter { $0 == string }
}
// Filter an input array of strings only for ones that are equal to a given string.
// filterByString(strings: [] as [String], string: "a") == [] as [String]
//
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] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
```
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 {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l2[i] = l[i]
}
}
l2.sort()
return l2
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the 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 l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l2[i] = l[i]
}
}
l2.sort()
return l2
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime.sort()
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var lPrime = l
for i in 0..<l.count {
if i % 3 == 0 {
lPrime.sort()
}
}
return lPrime
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 3 == 0 {
l.sort()
}
}
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l2[i] = l[i]
}
}
l2.sort()
return l2
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the 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 l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l2[i] = l[i]
}
}
l2.sort()
return l2
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// 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] {
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
func count(l: [Int], element: Int) -> Int {
var count = 0
for i in l {
if i == element {
count += 1
}
}
return count
}
func indexOf(l: [Int], element: Int) -> Int {
for i in 0..<l.count {
if l[i] == element {
return i
}
}
return -1
}
func lastIndexOf(l: [Int], element: Int) -> Int {
for i in (0..<l.count).reversed() {
if l[i] == element {
return i
}
}
return -1
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 3
func count(l: [Int], element: Int) -> Int {
var count = 0
for i in l {
if i == element {
count += 1
}
}
return count
}
// Return the index of the first occurrence of an element in an array
// indexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 1
func indexOf(l: [Int], element: Int) -> Int {
for i in 0..<l.count {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the last occurrence of an element in an array
// lastIndexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 5
func lastIndexOf(l: [Int], element: Int) -> Int {
for i in (0..<l.count).reversed() {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the first occurrence of an element in an array
// indexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 1
func indexOf(l: [Int], element: Int) -> Int {
for i in 0..<l.count {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the last occurrence of an element in an array
// lastIndexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 5
func lastIndexOf(l: [Int], element: Int) -> Int {
for i in (0..<l.count).reversed() {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the first occurrence of an element in an array
// indexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 1
func indexOf(l: [Int], element: Int) -> Int {
for i in 0..<l.count {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the last occurrence of an element in an array
// lastIndexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 5
func lastIndexOf(l: [Int], element: Int) -> Int {
for i in (0..<l.count).reversed() {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the first occurrence of an element in an array
// indexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) == 1
func indexOf(l: [Int], element: Int) -> Int {
for i in 0..<l.count {
if l[i] == element {
return i
}
}
return -1
}
// Return the index of the last occurrence of an element in an array
// lastIndexOf(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], element: 3) ==
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
```
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in 0..<l.count {
if !unique.contains(l[i]) {
unique.append(l[i])
}
}
return unique
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in 0..<l.count {
if !unique.contains(l[i]) {
unique.append(l[i])
}
}
return unique
}
print(unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]))
```
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if !unique.contains(i) {
unique.append(i)
}
}
return unique.sorted()
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
if i == n {
count += 1
}
}
return count
}
// Return the number of times an element appears in an array
// count(l: [5, 3, 5, 2, 3, 3, 9, 0, 123], n: 3) == 3
func count(l: [Int], n: Int) -> Int {
var count = 0
for i in l {
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func count(l: [Int]) -> Int {
var count = 0
for _ in l {
count += 1
}
return count
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func average(l: [Int]) -> Double {
var sum = 0
for i in l {
sum += i
}
return Double(sum) / Double(l.count)
}
func indexOf(l: [Int], element: Int) -> Int {
for (index, value) in l.enumerated() {
if value == element {
return index
}
}
return -1
}
func lastIndexOf(l: [Int], element: Int) -> Int {
for (index, value) in l.enumerated().reversed() {
if value == element {
return index
}
}
return -1
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// Return minimum element in the array.
// minElement(l: [1, 2, 3]) == 1
// minElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -10
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
// Return the number of elements in the array.
// count(l: [1, 2, 3]) == 3
// count(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 11
func count(l: [Int]) -> Int {
var count = 0
for _ in l {
count += 1
}
return count
}
// Return the sum of all elements in the array.
// sum(l: [1, 2, 3]) == 6
// sum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 106
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the average of all elements in the array.
// average(l: [1, 2, 3]) == 2
// average(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10.636363636363636
func average(l: [Int]) -> Double {
var sum = 0
for i in l {
sum += i
}
return Double(sum) / Double(l.count)
}
// Return the index of the first occurrence of the element in the array.
// indexOf(l: [1, 2, 3], element: 2) == 1
// indexOf(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10], element: 0) == 7
func indexOf(l: [Int], element: Int) -> Int {
for (index, value) in l.enumerated() {
if value == element {
return index
}
}
return -1
}
// Return the index of the last occurrence of the element in the array.
// lastIndexOf(l: [1, 2, 3], element: 2) == 1
// lastIndexOf(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10], element: 0) == 7
func lastIndexOf(l: [Int], element: Int) -> Int {
for (index, value) in l.enumerated().reversed() {
if value == element {
return index
}
}
return -1
}
// Return the index of the first occurrence of the element in the array.
// indexOf(l: [1, 2, 3], element: 2) == 1
// indexOf(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10], element: 0) == 7
func indexOf(l: [Int], element: Int) -> Int {
for (index, value) in l.enumerated() {
if value == element {
return index
}
}
return -1
}
// Return the index of the last occurrence of the element in the array.
// lastIndexOf(l: [1, 2, 3], element: 2) == 1
// lastIndexOf
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 0..<l.count {
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 0..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 0..<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 0..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 0..<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 0..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 0..<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 0..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 0..<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 0..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if String(i).contains("7") {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if String(i).contains("7") {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if String(i).contains("7") {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if String(i).contains("7") {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if String(i).contains("7") {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if String(i).contains("7") {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
count += String(i).filter { $0 == "7" }.count
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
count += String(i).filter { $0 == "7" }.count
}
}
return count
}
```
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
let str = String(i)
for char in str {
if char == "7" {
count += 1
}
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
let str = String(i)
for char in str {
if char == "7" {
count += 1
}
}
}
}
return count
}
```
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if i % 10 == 7 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
if i % 10 == 7 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i.description.contains("7") {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i.description.contains("7") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if (i % 11 == 0 || i % 13 == 0) && i % 10 == 7 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
let str = String(i)
for char in str {
if char == "7" {
count += 1
}
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 0..<n {
if i % 11 == 0 || i % 13 == 0 {
let str = String(i)
for char in str {
if char == "7" {
count += 1
}
}
}
}
return count
}
```
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in stride(from: 0, to: l.count, by: 2) {
let even = lPrime[i]
var j = i + 1
while j < lPrime.count && lPrime[j] < even {
j += 2
}
lPrime.insert(even, at: j)
lPrime.remove(at: i)
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in stride(from: 0, to: l.count, by: 2) {
let even = lPrime[i]
var j = i + 1
while j < lPrime.count && lPrime[j] < even {
j += 2
}
lPrime.insert(even, at: j)
lPrime.remove(at: i)
}
return lPrime
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in stride(from: 0, to: l.count, by: 2) {
var j = i
while j > 0 && lPrime[j] < lPrime[j - 1] {
let temp = lPrime[j]
lPrime[j] = lPrime[j - 1]
lPrime[j - 1] = temp
j -= 1
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in stride(from: 0, to: l.count, by: 2) {
var j = i
while j > 0 && lPrime[j] < lPrime[j - 1] {
let temp = lPrime[j]
lPrime[j] = lPrime[j - 1]
lPrime[j - 1] = temp
j -= 1
}
}
return lPrime
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 2 == 0 {
lPrime[i] = lPrime.sorted()[i]
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 2 == 0 {
lPrime[i] = lPrime.sorted()[i]
}
}
return lPrime
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
func sortOdd(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 1, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the even indicies, while its values at the odd indicies are equal
// to the values of the odd indicies of l, but sorted.
// sortOdd(l: [1, 2, 3]) == [1, 2, 3]
// sortOdd(l: [5, 6, 3, 4]) == [5, 6, 3, 4]
func sortOdd(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 1, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the even indicies, while its values at the odd indicies are equal
// to the values of the odd indicies of l, but sorted.
// sortOdd(l: [1, 2, 3]) == [1, 2, 3]
// sortOdd(l: [5, 6, 3, 4]) == [5, 6, 3, 4]
func sortOdd(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 1, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the even indicies, while its values at the odd indicies are equal
// to the values of the odd indicies of l, but sorted.
// sortOdd(l: [1, 2, 3]) == [1, 2, 3]
// sortOdd(l: [5, 6, 3, 4]) == [5, 6, 3, 4]
func sortOdd(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 1, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the even indicies, while its values at the odd indicies are equal
// to the values of the odd indicies of l, but sorted.
// sortOdd(l: [1, 2, 3]) == [1, 2, 3]
// sortOdd(l: [5, 6, 3, 4]) == [5, 6, 3, 4]
func sortOdd(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 1, to: l.count, by: 2) {
for j in stride(from: i+1, to: l.count, by: 2) {
if l[i] > l
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 2 == 0 {
lPrime[i] = lPrime[i]
} else {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 2 == 0 {
lPrime[i] = lPrime[i]
} else {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = lPrime[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 2 == 0 {
lPrime[i] = l[i]
} else {
lPrime[i] = l[i].sorted()
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 2 == 0 {
lPrime[i] = l[i]
} else {
lPrime[i] = l[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = l[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 2 == 0 {
lPrime[i] = lPrime[i]
} else {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 2 == 0 {
lPrime[i] = lPrime[i]
} else {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = lPrime[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 2 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if i % 2 == 0 {
lPrime[i] = l[i]
}
}
return lPrime
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 2 == 0 {
lPrime[i] = lPrime[i]
} else {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if i % 2 == 0 {
lPrime[i] = lPrime[i]
} else {
lPrime[i] = lPrime[i].sorted()
}
}
return lPrime
}
```
lPrime[i] = lPrime[i].sorted() // value of type 'Int' has no member 'sorted'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
for j in stride(from: i+2, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in stride(from: 0, to: l.count, by: 2) {
for j in stride(from: i+2, to: l.count, by: 2) {
if l[i] > l[j] {
let temp = l[i]
l[i] = l[j]
l[j] = temp
}
}
}
return l
}
```
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib.count < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
for i in 0..<fib.count {
if isPrime(fib[i]) {
return fib[i]
}
}
return -1
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib.count < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
for i in 0..<fib.count {
if isPrime(fib[i]) {
return fib[i]
}
}
return -1
}
// isPrime returns true if n is a prime number.
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
print(primeFib(n: 1))
print(primeFib(n: 2))
print(primeFib(n: 3))
print(primeFib(n: 4))
print(primeFib(n: 5))
```
if isPrime(fib[i]) { // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 0
while fib.count < n {
fib.append(fib[i] + fib[i + 1])
i += 1
}
var i = 0
while i < fib.count {
var isPrime = true
for j in 2..<fib[i] {
if fib[i] % j == 0 {
isPrime = false
break
}
}
if isPrime {
return fib[i]
}
i += 1
}
return 0
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 0
while fib.count < n {
fib.append(fib[i] + fib[i + 1])
i += 1
}
var i = 0
while i < fib.count {
var isPrime = true
for j in 2..<fib[i] {
if fib[i] % j == 0 {
isPrime = false
break
}
}
if isPrime {
return fib[i]
}
i += 1
}
return 0
}
```
var i = 0 // invalid redeclaration of 'i'
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib.count < n {
fib.append(fib[i-1] + fib[i-2])
i += 1
}
return fib.filter { isPrime($0) }[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 main() {
let n = 1000000
print(primeFib(n: n))
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib.count < n {
fib.append(fib[i-1] + fib[i-2])
i += 1
}
return fib.filter { isPrime($0) }[n-1]
}
// isPrime returns true if n is a prime number.
func isPrime(n: Int) -> Bool {
if n < 2 { return false }
for i in 2..<n {
if n % i == 0 { return false }
}
return true
}
// main prints the n-th prime Fibonacci number.
func main() {
let n = 1000000
print(primeFib(n: n))
}
main()
```
return fib.filter { isPrime($0) }[n-1] // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib.count < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var i = 0
while i < fib.count {
var j = 2
while j < fib[i] {
if fib[i] % j == 0 {
fib.remove(at: i)
break
}
j += 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 = [1, 1]
var i = 2
while fib.count < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var i = 0
while i < fib.count {
var j = 2
while j < fib[i] {
if fib[i] % j == 0 {
fib.remove(at: i)
break
}
j += 1
}
i += 1
}
return fib[n - 1]
}
```
var i = 0 // invalid redeclaration of 'i'
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 0
while fib.count < n {
fib.append(fib[i] + fib[i + 1])
i += 1
}
var i = 0
while fib[i] % 2 == 0 {
i += 1
}
var i = 0
while fib[i] % 3 == 0 {
i += 1
}
var i = 0
while fib[i] % 5 == 0 {
i += 1
}
var i = 0
while fib[i] % 7 == 0 {
i += 1
}
var i = 0
while fib[i] % 11 == 0 {
i += 1
}
var i = 0
while fib[i] % 13 == 0 {
i += 1
}
var i = 0
while fib[i] % 17 == 0 {
i += 1
}
var i = 0
while fib[i] % 19 == 0 {
i += 1
}
var i = 0
while fib[i] % 23 == 0 {
i += 1
}
var i = 0
while fib[i] % 29 == 0 {
i += 1
}
var i = 0
while fib[i] % 31 == 0 {
i += 1
}
var i = 0
while fib[i] % 37 == 0 {
i += 1
}
var i = 0
while fib[i] % 41 == 0 {
i += 1
}
var i = 0
while fib[i] % 43 == 0 {
i += 1
}
var i = 0
while fib[i] % 47 == 0 {
i += 1
}
var i = 0
while fib[i] % 53 == 0 {
i += 1
}
var i = 0
while fib[i] % 59 == 0 {
i += 1
}
var i = 0
while fib[i] % 61 == 0 {
i += 1
}
var i = 0
while fib[i] % 67 == 0 {
i += 1
}
var i = 0
while fib[i] % 71 == 0 {
i += 1
}
var i = 0
while fib[i] % 73 == 0 {
i += 1
}
var i = 0
while fib[i] % 79 == 0 {
i += 1
}
var i = 0
while fib[i] % 83 == 0 {
i += 1
}
var i = 0
while fib[i] % 89 == 0 {
i += 1
}
var i = 0
while fib[i] % 97 == 0 {
i += 1
}
var i = 0
while fib[i] % 101 == 0 {
i += 1
}
var i = 0
while fib[i] % 103 == 0 {
i += 1
}
var i = 0
while fib[i] % 107 == 0 {
i += 1
}
var i = 0
while fib[i] % 109 == 0 {
i += 1
}
var i = 0
while fib[i] % 113 == 0 {
i += 1
}
var i = 0
while fib[i] % 127 == 0 {
i += 1
}
var i = 0
XCTAssertTrue(primeFib(n: 1) == 2) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 2) == 3) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 3) == 5) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 4) == 13) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 5) == 89) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 6) == 233) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 7) == 1597) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 8) == 28657) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 9) == 514229) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 10) == 433494437) // cannot find 'primeFib' in scope
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(0)
fib.append(1)
for _ in 0..<n {
let next = fib[fib.count - 1] + fib[fib.count - 2]
fib.append(next)
}
for i in 0..<fib.count {
if isPrime(fib[i]) {
return fib[i]
}
}
return -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]()
fib.append(0)
fib.append(1)
for _ in 0..<n {
let next = fib[fib.count - 1] + fib[fib.count - 2]
fib.append(next)
}
for i in 0..<fib.count {
if isPrime(fib[i]) {
return fib[i]
}
}
return -1
}
// isPrime returns true if n is prime.
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
print(primeFib(n: 1))
print(primeFib(n: 2))
print(primeFib(n: 3))
print(primeFib(n: 4))
print(primeFib(n: 5))
print(primeFib(n: 6))
print(primeFib(n: 7))
print(primeFib(n: 8))
print(primeFib(n: 9))
print(primeFib(n: 10))
print(primeFib(n: 11))
print(primeFib(n: 12))
print(primeFib(n: 13))
print(primeFib(n: 14))
print(primeFib(n: 15))
print(primeFib(n: 16))
print(primeFib(n: 17))
print(primeFib(n: 18))
print(primeFib(n: 19))
print(primeFib(n: 20))
print(primeFib(n: 21))
print(primeFib(n: 22))
print(primeFib(n: 23))
print(primeFib(n: 24))
print(primeFib(n: 25))
print(primeFib(n: 26))
print(primeFib(n: 27))
print(primeFib(n: 28))
print(primeFib(n: 29))
print(primeFib(n: 30))
print(primeFib(n: 31))
print(primeFib(n: 32))
print(primeFib(n: 33))
print(primeFib(n: 34))
print(primeFib(n: 35))
print(primeFib(n: 36))
print(primeFib(n: 37))
print(primeFib(n: 38))
print(primeFib(n: 39))
print(primeFib(n: 40))
print(primeFib(n: 41))
print(primeFib(n: 42))
print(primeFib(n: 43))
print(primeFib(n: 44))
print(primeFib(n: 45))
print(primeFib(n: 46))
print(primeFib(n: 47))
print(primeFib(n: 48))
print(primeFib(n: 49))
print(primeFib(n: 50))
print(primeFib(n: 51))
print(primeFib(n: 52))
print(primeFib(n: 53))
print(primeFib(n: 54))
print(primeFib(n: 55))
print(primeFib(n: 56))
print(primeFib(n: 57))
print(primeFib(n: 58))
print(primeFib(n: 59))
print(primeFib(n: 60))
print(primeFib(n: 61))
print(primeFib(n: 62))
print(primeFib(n: 63))
print(primeFib(n: 64))
print(primeFib(n: 65))
print(primeFib(n: 66))
print(primeFib(n: 67))
print(primeFib(n: 68))
print(primeFib(n: 69))
print(primeFib(n: 70))
print(primeFib(n
if isPrime(fib[i]) { // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib.count < n {
fib.append(fib[i-1] + fib[i-2])
i += 1
}
var j = 0
while j < fib.count {
var isPrime = true
var k = 2
while k < fib[j] {
if fib[j] % k == 0 {
isPrime = false
break
}
k += 1
}
if isPrime {
return fib[j]
}
j += 1
}
return -1
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib.count < n {
fib.append(fib[i-1] + fib[i-2])
i += 1
}
var j = 0
while j < fib.count {
var isPrime = true
var k = 2
while k < fib[j] {
if fib[j] % k == 0 {
isPrime = false
break
}
k += 1
}
if isPrime {
return fib[j]
}
j += 1
}
return -1
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(0)
fib.append(1)
for _ in 0..<n {
let next = fib[fib.count - 1] + fib[fib.count - 2]
fib.append(next)
}
for i in 0..<fib.count {
if isPrime(fib[i]) {
return fib[i]
}
}
return 0
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(0)
fib.append(1)
for _ in 0..<n {
let next = fib[fib.count - 1] + fib[fib.count - 2]
fib.append(next)
}
for i in 0..<fib.count {
if isPrime(fib[i]) {
return fib[i]
}
}
return 0
}
// isPrime returns true if the number is prime.
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
print(primeFib(n: 1))
print(primeFib(n: 2))
print(primeFib(n: 3))
print(primeFib(n: 4))
print(primeFib(n: 5))
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(1)
fib.append(2)
var i = 2
while fib.count < n {
fib.append(fib[i-1] + fib[i-2])
i += 1
}
var j = 0
while j < fib.count {
var isPrime = true
var k = 2
while k < fib[j] {
if fib[j] % k == 0 {
isPrime = false
break
}
k += 1
}
if isPrime {
return fib[j]
}
j += 1
}
return 0
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(1)
fib.append(2)
var i = 2
while fib.count < n {
fib.append(fib[i-1] + fib[i-2])
i += 1
}
var j = 0
while j < fib.count {
var isPrime = true
var k = 2
while k < fib[j] {
if fib[j] % k == 0 {
isPrime = false
break
}
k += 1
}
if isPrime {
return fib[j]
}
j += 1
}
return 0
}
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 0
var count = 0
while count < n {
c = a + b
a = b
b = c
if isPrime(n: c) {
count += 1
}
}
return c
}
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 a = 1
var b = 1
var c = 0
var count = 0
while count < n {
c = a + b
a = b
b = c
if isPrime(n: c) {
count += 1
}
}
return c
}
// isPrime returns true if n is a prime number.
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 {
// 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
}
// Test cases
print(triplesSumToZero(l: [1, 3, 5, 0]))
print(triplesSumToZero(l: [1, 3, -2, 1]))
print(triplesSumToZero(l: [1, 2, 3, 7]))
print(triplesSumToZero(l: [2, 4, -5, 3, 9, 7]))
print(triplesSumToZero(l: [1]))
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
let l = l.sorted()
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let l = l.sorted()
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool {
let l = l.sorted()
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let l = l.sorted()
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool {
// 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.
}
// Uncomment the line below when you're ready to try out your function.
print(triplesSumToZero(l: [1, 3, -2, 1]))
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(-sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```swift
// 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 seen = Set<Int>()
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(-sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
return false
}
// triplesSumToZero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: your code here
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// TODO: your code here
}
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
var seen: Set<Int> = []
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(-sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```swift
// 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 seen: Set<Int> = []
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(-sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```
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.
}
// Example 1
print(triplesSumToZero(l: [1, 3, 5, 0]))
// Example 2
print(triplesSumToZero(l: [1, 3, -2, 1]))
// Example 3
print(triplesSumToZero(l: [1, 2, 3, 7]))
// Example 4
print(triplesSumToZero(l: [2, 4, -5, 3, 9, 7]))
// Example 5
print(triplesSumToZero(l: [1]))
```
} // missing return in global function expected to return 'Bool'
func triplesSumToZero(l: [Int]) -> Bool {
var seen: Set<Int> = []
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(-sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```swift
// 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 seen: Set<Int> = []
for i in 0..<l.count {
for j in i+1..<l.count {
let sum = l[i] + l[j]
if seen.contains(-sum) {
return true
}
seen.insert(sum)
}
}
return false
}
```
func carRaceCollision(n: Int) -> Int {
var left = 0
var right = n - 1
var count = 0
while left < right {
count += 1
left += 1
right -= 1
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var left = 0
var right = n - 1
var count = 0
while left < right {
count += 1
left += 1
right -= 1
}
return count
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
print(carRaceCollision(n: 3))
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var leftCars = [Int]()
var rightCars = [Int]()
for i in 0..<n {
leftCars.append(i)
rightCars.append(n - i - 1)
}
var leftIndex = 0
var rightIndex = 0
var collisions = 0
while leftIndex < n && rightIndex < n {
if leftCars[leftIndex] < rightCars[rightIndex] {
leftIndex += 1
} else {
rightIndex += 1
}
if leftCars[leftIndex] == rightCars[rightIndex] {
collisions += 1
leftIndex += 1
rightIndex += 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 leftCars = [Int]()
var rightCars = [Int]()
for i in 0..<n {
leftCars.append(i)
rightCars.append(n - i - 1)
}
var leftIndex = 0
var rightIndex = 0
var collisions = 0
while leftIndex < n && rightIndex < n {
if leftCars[leftIndex] < rightCars[rightIndex] {
leftIndex += 1
} else {
rightIndex += 1
}
if leftCars[leftIndex] == rightCars[rightIndex] {
collisions += 1
leftIndex += 1
rightIndex += 1
}
}
return collisions
}
```
// XCTAssertTrue failed
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var left = 0
var right = n - 1
var count = 0
while left < right {
if left == right {
break
}
if left + 1 == right {
count += 1
break
}
if left + 2 == right {
count += 1
break
}
if left + 3 == right {
count += 1
break
}
if left + 4 == right {
count += 1
break
}
if left + 5 == right {
count += 1
break
}
if left + 6 == right {
count += 1
break
}
if left + 7 == right {
count += 1
break
}
if left + 8 == right {
count += 1
break
}
if left + 9 == right {
count += 1
break
}
if left + 10 == right {
count += 1
break
}
if left + 11 == right {
count += 1
break
}
if left + 12 == right {
count += 1
break
}
if left + 13 == right {
count += 1
break
}
if left + 14 == right {
count += 1
break
}
if left + 15 == right {
count += 1
break
}
if left + 16 == right {
count += 1
break
}
if left + 17 == right {
count += 1
break
}
if left + 18 == right {
count += 1
break
}
if left + 19 == right {
count += 1
break
}
if left + 20 == right {
count += 1
break
}
if left + 21 == right {
count += 1
break
}
if left + 22 == right {
count += 1
break
}
if left + 23 == right {
count += 1
break
}
if left + 24 == right {
count += 1
break
}
if left + 25 == right {
count += 1
break
}
if left + 26 == right {
count += 1
break
}
if left + 27 == right {
count += 1
break
}
if left + 28 == right {
count += 1
break
}
if left + 29 == right {
count += 1
break
}
if left + 30 == right {
count += 1
break
}
if left + 31 == right {
count += 1
break
}
if left + 32 == right {
count += 1
break
}
if left + 33 == right {
count += 1
break
}
if left + 34 == right {
count += 1
break
}
if left + 35 == right {
count += 1
break
}
if left + 36 == right {
count += 1
break
}
if left + 37 == right {
count += 1
break
}
if left + 38 == right {
count += 1
break
}
if left + 39 == right {
count += 1
break
}
if left + 40 == right {
count += 1
break
}
if left + 41 == right {
count += 1
break
}
if left + 42 == right {
count += 1
break
}
if left + 43 == right {
count += 1
break
}
XCTAssertTrue(carRaceCollision(n: 2) == 4) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 3) == 9) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 4) == 16) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 8) == 64) // cannot find 'carRaceCollision' in scope
XCTAssertTrue(carRaceCollision(n: 10) == 100) // cannot find 'carRaceCollision' in scope
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 0
var right = n - 1
while left < right {
collisions += 1
left += 1
right -= 1
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 0
var right = n - 1
while left < right {
collisions += 1
left += 1
right -= 1
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var left = Array(repeating: 0, count: n)
var right = Array(repeating: 0, count: n)
var count = 0
for i in 0..<n {
left[i] = i
right[i] = n - 1 - i
}
for i in 0..<n {
for j in 0..<n {
if left[i] == right[j] {
count += 1
}
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var left = Array(repeating: 0, count: n)
var right = Array(repeating: 0, count: n)
var count = 0
for i in 0..<n {
left[i] = i
right[i] = n - 1 - i
}
for i in 0..<n {
for j in 0..<n {
if left[i] == right[j] {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 0
var right = n - 1
while left < right {
collisions += 1
left += 1
right -= 1
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
var left = 0
var right = n - 1
while left < right {
collisions += 1
left += 1
right -= 1
}
return collisions
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var count = 0
for i in 0..<n {
for j in 0..<n {
if i != j {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] = l[i] + 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] = l[i] + 1
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result: [Int] = []
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result: [Int] = []
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] = l[i] + 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] = l[i] + 1
}
return result
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(-num) {
return true
}
seen.insert(num)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(-num) {
return true
}
seen.insert(num)
}
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: Write your code here.
}
```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: Write your code here.
}
// Uncomment the lines below when you're ready to try out your function!
print(pairsSumToZero(l: [1, 3, 5, 0]))
print(pairsSumToZero(l: [1, 3, -2, 1]))
print(pairsSumToZero(l: [1, 2, 3, 7]))
print(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]))
print(pairsSumToZero(l: [1]))
```
} // missing return in global function expected to return 'Bool'
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
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: Write your code here
return false
}
```
// XCTAssertTrue failed
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(-num) {
return true
}
seen.insert(num)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(-num) {
return true
}
seen.insert(num)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
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: Write your code here
return false
}
```
// XCTAssertTrue failed
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
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: Write your code here
return false
}
```
// XCTAssertTrue failed
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
func pairsSumToZero2(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
func pairsSumToZero3(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
func pairsSumToZero4(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
func pairsSumToZero5(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
func pairsSumToZero6(l: [Int]) -> Bool {
// TODO: Write your code here.
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: Write your code here.
return false
}
// pairsSumToZero2 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.
// pairsSumToZero2(l: [1, 3, 5, 0]) == false
// pairsSumToZero2(l: [1, 3, -2, 1]) == false
// pairsSumToZero2(l: [1, 2, 3, 7]) == false
// pairsSumToZero2(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero2(l: [1]) == false
func pairsSumToZero2(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
// pairsSumToZero3 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.
// pairsSumToZero3(l: [1, 3, 5, 0]) == false
// pairsSumToZero3(l: [1, 3, -2, 1]) == false
// pairsSumToZero3(l: [1, 2, 3, 7]) == false
// pairsSumToZero3(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero3(l: [1]) == false
func pairsSumToZero3(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
// pairsSumToZero4 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.
// pairsSumToZero4(l: [1, 3, 5, 0]) == false
// pairsSumToZero4(l: [1, 3, -2, 1]) == false
// pairsSumToZero4(l: [1, 2, 3, 7]) == false
// pairsSumToZero4(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero4(l: [1]) == false
func pairsSumToZero4(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
// pairsSumToZero5 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.
// pairsSumToZero5(l: [1, 3, 5, 0]) == false
// pairsSumToZero5(l: [1, 3, -2, 1]) == false
// pairsSumToZero5(l: [1, 2, 3, 7]) == false
// pairsSumToZero5(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero5(l: [1]) == false
func pairsSumToZero5(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
// pairsSumToZero6 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.
// pairsSumToZero6(l: [1, 3, 5, 0]) == false
// pairsSumToZero6(l: [1, 3, -2, 1]) == false
// pairsSumToZero6(l: [1, 2, 3, 7]) == false
// pairsSumToZero6(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero6(l: [1]) == false
func pairsSumToZero6(l: [Int]) -> Bool {
// TODO: Write your code here.
return false
}
// pairsSumToZero7 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.
// pairsSumToZero7(l: [1, 3,
// XCTAssertTrue failed
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(num) {
return true
}
seen.insert(-num)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(num) {
return true
}
seen.insert(-num)
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
// TODO: Write your code here
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: Write your code here
return false
}
// Test cases
print(pairsSumToZero(l: [1, 3, 5, 0]))
print(pairsSumToZero(l: [1, 3, -2, 1]))
print(pairsSumToZero(l: [1, 2, 3, 7]))
print(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]))
print(pairsSumToZero(l: [1]))
```
// XCTAssertTrue failed
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = "\(temp % base)" + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = "\(temp % base)" + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
while number > 0 {
result = String(number % base) + result
number = number / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
while number > 0 {
result = String(number % base) + result
number = number / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
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
while x > 0 {
result = "\(x % base)" + result
x = x / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
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
while x > 0 {
result = "\(x % base)" + result
x = x / base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var temp = x
while temp > 0 {
result = String(temp % base) + result
temp = temp / base
}
return result
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
// Given
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2.0
}
```
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
func triangleArea(a: Int32, h: Int32) -> Int32 {
return a * h / 2
}
func triangleArea(a: Int64, h: Int64) -> Int64 {
return a * h / 2
}
func triangleArea(a: UInt, h: UInt) -> UInt {
return a * h / 2
}
func triangleArea(a: UInt32, h: UInt32) -> UInt32 {
return a * h / 2
}
func triangleArea(a: UInt64, h: UInt64) -> UInt64 {
return a * h / 2
}
func triangleArea(a: Int8, h: Int8) -> Int8 {
return a * h / 2
}
func triangleArea(a: UInt8, h: UInt8) -> UInt8 {
return a * h / 2
}
func triangleArea(a: Int16, h: Int16) -> Int16 {
return a * h / 2
}
func triangleArea(a: UInt16, h: UInt16) -> UInt16 {
return a * h / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int32, h: Int32) -> Int32 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int64, h: Int64) -> Int64 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: UInt, h: UInt) -> UInt {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: UInt32, h: UInt32) -> UInt32 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: UInt64, h: UInt64) -> UInt64 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int8, h: Int8) -> Int8 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: UInt8, h: UInt8) -> UInt8 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int16, h: Int16) -> Int16 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: UInt16, h: UInt16) -> UInt16 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int32, h: Int32) -> Int32 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: UInt32, h: UInt32) -> UInt32 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int64, h: Int64) -> Int64 {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
func triangleArea(a: Int, h: Int) -> Int {
return a * h / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Int {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Int {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Int {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Double, h: Double) -> Double {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Float, h: Float) -> Float {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: CGFloat, h: CGFloat) -> CGFloat {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Int {
return a * h / 2
}
// Given length of a side and high return area for a triangle.
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
var e = 0
for i in 0..<n {
if i % 4 == 0 {
a = b
} else if i % 4 == 1 {
b = c
} else if i % 4 == 2 {
c = d
} else if i % 4 == 3 {
d = e
}
e = a + b + c + d
}
return e
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
var e = 0
for i in 0..<n {
if i % 4 == 0 {
a = b
} else if i % 4 == 1 {
b = c
} else if i % 4 == 2 {
c = d
} else if i % 4 == 3 {
d = e
}
e = a + b + c + d
}
return e
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i - 1] + fib4[i - 2] + fib4[i - 3] + fib4[i - 4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i - 1] + fib4[i - 2] + fib4[i - 3] + fib4[i - 4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
let temp = a
a = b
b = c
c = d
d = temp + b + c + d
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 0..<n {
let temp = a
a = b
b = c
c = d
d = temp + b + c + d
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 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 - 1] + sorted[count / 2]) / 2
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 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 - 1] + sorted[count / 2]) / 2
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 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 - 1] + sorted[count / 2]) / 2
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 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 - 1] + sorted[count / 2]) / 2.0
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
// 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
// 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
// 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
// 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
// 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid - 1]) / 2
} else {
return Double(sorted[count / 2])
}
}
// 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 = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(sorted[mid] + sorted[mid -
func median(l: [Int]) -> Double {
var l = l
l.sort()
let count = l.count
if count % 2 == 0 {
return Double(l[count / 2 - 1] + l[count / 2]) / 2.0
} else {
return Double(l[count / 2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
var l = l
l.sort()
let count = l.count
if count % 2 == 0 {
return Double(l[count / 2 - 1] + l[count / 2]) / 2.0
} else {
return Double(l[count / 2])
}
}
```
func median(l: [Int]) -> Double {
var l = l
l.sort()
let count = l.count
if count % 2 == 0 {
return Double(l[count / 2 - 1] + l[count / 2]) / 2
} else {
return Double(l[count / 2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
var l = l
l.sort()
let count = l.count
if count % 2 == 0 {
return Double(l[count / 2 - 1] + l[count / 2]) / 2
} else {
return Double(l[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = l.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 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 = l.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 2
} else {
return Double(sorted[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let l = l.sorted()
let count = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(l[mid] + l[mid - 1]) / 2
} else {
return Double(l[count / 2])
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let l = l.sorted()
let count = l.count
if count % 2 == 0 {
let mid = count / 2
return Double(l[mid] + l[mid - 1]) / 2
} else {
return Double(l[count / 2])
}
}
```
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let count = sorted.count
if count % 2 == 0 {
return Double(sorted[count / 2 - 1] + sorted[count / 2]) / 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 - 1] + sorted[count / 2]) / 2
} else {
return Double(sorted[count / 2])
}
}
```
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let text = text.replacingOccurrences(of: " ", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: ".", with: "")
let text = text.replacingOccurrences(of: ",", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of:
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textWithoutSpaces = text.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharacters = textWithoutSpaces.replacingOccurrences(of: "[^a-zA-Z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpaces = textWithoutSpecialCharacters.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharactersAndSpacesAndNumbers = textWithoutSpecialCharactersAndSpaces.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbers.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbers.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbers.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbers.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndUppercaseAndLowercaseAndNumbersAndUppercaseAnd
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textArray = Array(text)
let textArrayReversed = textArray.reversed()
for (index, char) in textArray.enumerated() {
if char != textArrayReversed[index] {
return false
}
}
return true
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textArray = Array(text)
let textArrayReversed = textArray.reversed()
for (index, char) in textArray.enumerated() {
if char != textArrayReversed[index] {
return false
}
}
return true
}
```
if char != textArrayReversed[index] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<[String.Element]>.Index' (aka 'ReversedCollection<Array<Character>>.Index')
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let text = text.replacingOccurrences(of: " ", with: "")
let text = text.replacingOccurrences(of: ",", with: "")
let text = text.replacingOccurrences(of: ".", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: "[", with: "")
let text = text.replacingOccurrences(of: "]", with: "")
let text = text.replacingOccurrences(of: "{", with: "")
let text = text.replacingOccurrences(of: "}", with: "")
let text = text.replacingOccurrences(of: "1", with: "")
let text = text.replacingOccurrences(of: "2", with: "")
let text = text.replacingOccurrences(of: "3", with: "")
let text = text.replacingOccurrences(of: "4", with: "")
let text = text.replacingOccurrences(of: "5", with: "")
let text = text.replacingOccurrences(of: "6", with: "")
let text = text.replacingOccurrences(of: "7", with: "")
let text = text.replacingOccurrences(of: "8", with: "")
let text = text.replacingOccurrences(of: "9", with: "")
let text = text.replacingOccurrences(of: "0", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "@", with: "")
let text = text.replacingOccurrences(of: "#", with: "")
let text = text.replacingOccurrences(of: "$", with: "")
let text = text.replacingOccurrences(of: "%", with: "")
let text = text.replacingOccurrences(of: "^", with: "")
let text = text.replacingOccurrences(of: "&", with: "")
let text = text.replacingOccurrences(of: "*", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: "-", with: "")
let text = text.replacingOccurrences(of: "_", with: "")
let text = text.replacingOccurrences(of: "=", with: "")
let text = text.replacingOccurrences(of: "+", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "/", with: "")
let text = text.replacingOccurrences(of: "\\", with: "")
let text = text.replacingOccurrences(of: "|", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: ">", with: "")
let text = text.replacingOccurrences(of: "<", with: "")
let text = text.replacingOccurrences(of: " ", with: "")
let text = text.replacingOccurrences(of: "\n", with: "")
let text = text.replacingOccurrences(of: "\t", with: "")
let text = text.replacingOccurrences(of: "\r", with: "")
let text = text.replacingOccurrences(of: "\"", with: "")
let text = text.replacingOccurrences(of: "\'", with: "")
let text = text.replacingOccurrences(of: "\r", with: "")
let text = text.replacingOccurrences(of: "\n", with: "")
let text = text.replacingOccurrences(of: "\t", with: "")
let text = text.replacingOccurrences(of: "\r", with: "")
let text = text.replacingOccurrences(of: "\n", with: "")
let text = text.replacingOccurrences(of: "\t", with: "")
let text = text.replacingOccurrences(of: "\r", with: "")
let text = text.replacingOccurrences(of:
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let text = text.replacingOccurrences(of: " ", with: "")
let text = text.replacingOccurrences(of: ",", with: "")
let text = text.replacingOccurrences(of: ".", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: "[", with: "")
let text = text.replacingOccurrences(of: "]", with: "")
let text = text.replacingOccurrences(of: "{", with: "")
let text = text.replacingOccurrences(of: "}", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "@", with: "")
let text = text.replacingOccurrences(of: "#", with: "")
let text = text.replacingOccurrences(of: "$", with: "")
let text = text.replacingOccurrences(of: "%", with: "")
let text = text.replacingOccurrences(of: "^", with: "")
let text = text.replacingOccurrences(of: "&", with: "")
let text = text.replacingOccurrences(of: "*", with: "")
let text = text.replacingOccurrences(of: "/", with: "")
let text = text.replacingOccurrences(of: "\\", with: "")
let text = text.replacingOccurrences(of: "|", with: "")
let text = text.replacingOccurrences(of: "`", with: "")
let text = text.replacingOccurrences(of: "~", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with:
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textWithoutSpaces = text.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharacters = textWithoutSpaces.replacingOccurrences(of: "[^a-zA-Z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpaces = textWithoutSpecialCharacters.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharactersAndSpacesReversed = String(textWithoutSpecialCharactersAndSpaces.reversed())
return textWithoutSpecialCharactersAndSpaces == textWithoutSpecialCharactersAndSpacesReversed
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textWithoutSpaces = text.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharacters = textWithoutSpaces.replacingOccurrences(of: "[^a-zA-Z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpaces = textWithoutSpecialCharacters.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharactersAndSpacesReversed = String(textWithoutSpecialCharactersAndSpaces.reversed())
return textWithoutSpecialCharactersAndSpaces == textWithoutSpecialCharactersAndSpacesReversed
}
```
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let text = text.replacingOccurrences(of: " ", with: "")
let text = text.replacingOccurrences(of: ",", with: "")
let text = text.replacingOccurrences(of: ".", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: "[", with: "")
let text = text.replacingOccurrences(of: "]", with: "")
let text = text.replacingOccurrences(of: "{", with: "")
let text = text.replacingOccurrences(of: "}", with: "")
let text = text.replacingOccurrences(of: "1", with: "")
let text = text.replacingOccurrences(of: "2", with: "")
let text = text.replacingOccurrences(of: "3", with: "")
let text = text.replacingOccurrences(of: "4", with: "")
let text = text.replacingOccurrences(of: "5", with: "")
let text = text.replacingOccurrences(of: "6", with: "")
let text = text.replacingOccurrences(of: "7", with: "")
let text = text.replacingOccurrences(of: "8", with: "")
let text = text.replacingOccurrences(of: "9", with: "")
let text = text.replacingOccurrences(of: "0", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "@", with: "")
let text = text.replacingOccurrences(of: "#", with: "")
let text = text.replacingOccurrences(of: "$", with: "")
let text = text.replacingOccurrences(of: "%", with: "")
let text = text.replacingOccurrences(of: "^", with: "")
let text = text.replacingOccurrences(of: "&", with: "")
let text = text.replacingOccurrences(of: "*", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: "-", with: "")
let text = text.replacingOccurrences(of: "_", with: "")
let text = text.replacingOccurrences(of: "+", with: "")
let text = text.replacingOccurrences(of: "=", with: "")
let text = text.replacingOccurrences(of: "/", with: "")
let text = text.replacingOccurrences(of: "\\", with: "")
let text = text.replacingOccurrences(of: "|", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "<", with: "")
let text = text.replacingOccurrences(of: ">", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "\"", with: "")
let text = text.replacingOccurrences(of: "'", with: "")
let text = text.replacingOccurrences(of: "`", with: "")
let text = text.replacingOccurrences(of: "~", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´", with: "")
let text = text.replacingOccurrences(of: "´",
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textWithoutSpaces = text.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharacters = textWithoutSpaces.replacingOccurrences(of: "[^A-Za-z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpaces = textWithoutSpecialCharacters.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharactersAndSpacesAndNumbers = textWithoutSpecialCharactersAndSpaces.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuation = textWithoutSpecialCharactersAndSpacesAndNumbers.replacingOccurrences(of: "[^A-Za-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuation.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuation = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbers.replacingOccurrences(of: "[^A-Za-z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuation.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuation = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbers.replacingOccurrences(of: "[^A-Za-z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuation.replacingOccurrences(of: "[A-Z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercase = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercase.replacingOccurrences(of: "[a-z]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbers = textWithoutSpecialCharactersAndSpacesAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercaseAndNumbersAndPunctuationAndUppercaseAndLowercase.replacingOccurrences(of: "[0-9]", with: "", options
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let text = text.replacingOccurrences(of: " ", with: "")
let text = text.replacingOccurrences(of: "!", with: "")
let text = text.replacingOccurrences(of: "?", with: "")
let text = text.replacingOccurrences(of: ".", with: "")
let text = text.replacingOccurrences(of: ",", with: "")
let text = text.replacingOccurrences(of: ":", with: "")
let text = text.replacingOccurrences(of: ";", with: "")
let text = text.replacingOccurrences(of: "(", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of: ")", with: "")
let text = text.replacingOccurrences(of:
XCTAssertTrue(isPalindrome(text: "") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aba") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "aaaaa") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "zbcd") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyx") == true) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywyz") == false) // cannot find 'isPalindrome' in scope
XCTAssertTrue(isPalindrome(text: "xywzx") == false) // cannot find 'isPalindrome' in scope
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textWithoutSpaces = text.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharacters = textWithoutSpaces.replacingOccurrences(of: "[^a-zA-Z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpaces = textWithoutSpecialCharacters.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharactersAndSpacesReversed = String(textWithoutSpecialCharactersAndSpaces.reversed())
return textWithoutSpecialCharactersAndSpaces == textWithoutSpecialCharactersAndSpacesReversed
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let text = text.lowercased()
let textWithoutSpaces = text.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharacters = textWithoutSpaces.replacingOccurrences(of: "[^a-zA-Z0-9]", with: "", options: .regularExpression)
let textWithoutSpecialCharactersAndSpaces = textWithoutSpecialCharacters.replacingOccurrences(of: " ", with: "")
let textWithoutSpecialCharactersAndSpacesReversed = String(textWithoutSpecialCharactersAndSpaces.reversed())
return textWithoutSpecialCharactersAndSpaces == textWithoutSpecialCharactersAndSpacesReversed
}
```
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n & 1 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = 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
var power = 1
while n > 0 {
if n & 1 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = n >> 1
}
return result
}
```
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var result = 1
var n = n
var p = p
while n > 0 {
if n & 1 == 1 {
result = (result * p) % p
}
n = n >> 1
p = (p * p) % p
}
return result
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var result = 1
var n = n
var p = p
while n > 0 {
if n & 1 == 1 {
result = (result * p) % p
}
n = n >> 1
p = (p * p) % p
}
return result
}
```
// Fatal error: Division by zero in remainder operation
```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 i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = n
var p = p
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
while (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1) {
if (1)
XCTAssertTrue(modp(n: 3, p: 5) == 3) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 1101, p: 101) == 2) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 0, p: 101) == 1) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 3, p: 11) == 8) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 100, p: 101) == 1) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 30, p: 5) == 4) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 31, p: 5) == 3) // cannot find 'modp' in scope
func modp(n: Int, p: Int) -> Int {
var result = 1
var n = n
var p = p
var i = 0
while n > 0 {
if n % 2 == 1 {
result = (result * p) % 101
}
n = n / 2
p = (p * p) % 101
i += 1
}
return result
}
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 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 n = n
var p = p
var i = 0
while n > 0 {
if n % 2 == 1 {
result = (result * p) % 101
}
n = n / 2
p = (p * p) % 101
i += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n = n / 10
result += 1
}
return result
}
// Return the number of digits of n.
// digits(n: 1) == 1
// digits(n: 10) == 2
// digits(n: 100) == 3
func digits(n: Int) -> Int {
var result = 0
var n = n
while n > 0 {
n =
// XCTAssertTrue failed
```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 i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = n
var p = p
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
while n > 0 {
i = n % 10
j = p % 10
k = (i * j) % 10
l = (k + (i * j) / 10) % 10
m = (l + (k + (i * j) / 10) / 10) % 10
n = n / 10
p = p / 10
q = (m + (l + (k + (i * j) / 10) / 10) / 10) % 10
r = (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) % 10
s = (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) % 10
t = (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) % 10
u = (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) / 10) % 10
v = (u + (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) % 10
w = (v + (u + (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) % 10
x = (w + (v + (u + (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) % 10
y = (x + (w + (v + (u + (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) % 10
z = (y + (x + (w + (v + (u + (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) / 10) % 10
result = (z + (y + (x + (w + (v + (u + (t + (s + (r + (q + (m + (l + (k + (i * j) / 10) / 10) / 10)
XCTAssertTrue(modp(n: 3, p: 5) == 3) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 1101, p: 101) == 2) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 0, p: 101) == 1) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 3, p: 11) == 8) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 100, p: 101) == 1) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 30, p: 5) == 4) // cannot find 'modp' in scope
XCTAssertTrue(modp(n: 31, p: 5) == 3) // cannot find 'modp' in scope
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n & 1 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = 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
var power = 1
while n > 0 {
if n & 1 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = n >> 1
}
return result
}
```
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var result = 1
var i = 0
while i < n {
result = (result * 2) % p
i = i + 1
}
return result
}
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 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 i = 0
while i < n {
result = (result * 2) % p
i = i + 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
return result
}
// Return the number of bits in the number n.
// bitcount(n: 1) == 1
// bitcount(n: 100) == 7
func bitcount(n: Int) -> Int {
var result = 0
var i = n
while i > 0 {
result = result + 1
i = i >> 1
}
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n % 2 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = n / 2
}
return result
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n % 2 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = n / 2
}
return result
}
```
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n % 2 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n /= 2
}
return result
}
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 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
var power = 1
while n > 0 {
if n % 2 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n /= 2
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n > 0 {
n /= 10
result += 1
}
return result
}
// Return the number of digits of a number.
// digits(1) == 1
// digits(10) == 2
// digits(100) == 3
// digits(1000) == 4
func digits(n: Int) -> Int {
var n = n
var result = 0
while n >
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n % 2 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = n / 2
}
return result
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var result = 1
var power = 1
while n > 0 {
if n % 2 == 1 {
result = (result * power) % p
}
power = (power * power) % p
n = n / 2
}
return result
}
```
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char).lowercased()) {
newText += String(char)
}
}
return newText
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char).lowercased()) {
newText += String(char)
}
}
return newText
}
```
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var newText = ""
for char in text {
if !vowels.contains(String(char)) {
newText += String(char)
}
}
return newText
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in text {
if !vowels.contains(String(char)) {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i >= t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i >= t {
return false
}
}
return true
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
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
}
```
```swift
// Add
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
}
```
```swift
// Multiply
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
}
```
```swift
// Add
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
}
```
```swift
// Add
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Double {
return Double(x) / Double(y)
}
func remainder(x: Int, y: Int) -> Int {
return x % y
}
func squareRoot(x: Int) -> Double {
return sqrt(Double(x))
}
func square(x: Int) -> Int {
return x * x
}
func cube(x: Int) -> Int {
return x * x * x
}
func absoluteValue(x: Int) -> Int {
return abs(x)
}
func sine(x: Double) -> Double {
return sin(x)
}
func cosine(x: Double) -> Double {
return cos(x)
}
func tangent(x: Double) -> Double {
return tan(x)
}
func naturalLogarithm(x: Double) -> Double {
return log(x)
}
func base10Logarithm(x: Double) -> Double {
return log10(x)
}
func baseEExponential(x: Double) -> Double {
return exp(x)
}
func base10Exponential(x: Double) -> Double {
return pow(10, x)
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 10, y: 5) == 5
// subtract(x: 7, y: 3) == 4
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 10, y: 5) == 2
// divide(x: 7, y: 3) == 2.3333333333333335
func divide(x: Int, y: Int) -> Double {
return Double(x) / Double(y)
}
// Find the remainder of x divided by y
// remainder(x: 10, y: 5) == 0
// remainder(x: 7, y: 3) == 1
func remainder(x: Int, y: Int) -> Int {
return x % y
}
// Find the square root of x
// squareRoot(x: 16) == 4
// squareRoot(x: 9) == 3
func squareRoot(x: Int) -> Double {
return sqrt(Double(x))
}
// Find the square of x
// square(x: 2) == 4
// square(x: 3) == 9
func square(x: Int) -> Int {
return x * x
}
// Find the cube of x
// cube(x: 2) == 8
// cube(x: 3) == 27
func cube(x: Int) -> Int {
return x * x * x
}
// Find the absolute value of x
// absoluteValue(x: -5) == 5
// absoluteValue(x: 5) == 5
func absoluteValue(x: Int) -> Int {
return abs(x)
}
// Find the sine of x
// sine(x: 0) == 0
// sine(x: 90) == 1
func sine(x: Double) -> Double {
return sin(x)
}
// Find the cosine of x
// cosine(x: 0) == 1
// cosine(x: 90) == 0
func cosine(x: Double) -> Double {
return cos(x)
}
// Find the tangent of x
// tangent(x: 0) == 0
// tangent(x: 45) == 1
func tangent(x: Double) -> Double {
return tan(x)
}
// Find the natural logarithm of x
// naturalLogarithm(x: 1) == 0
// naturalLogarithm(x: 10) == 2.302585092994046
func naturalLogarithm(x: Double) -> Double {
return log(x)
}
// Find the base 10 logarithm of x
// base10Logarithm(x: 1) == 0
// base10Logarithm(x: 100) == 2
func base10Logarithm(x: Double) -> Double {
return log10(x)
}
// Find the base e exponential of x
// baseEExponential(x: 0) == 1
// baseEExponential(x: 1) == 2.718281828459045
func baseEExponential(x: Double) -> Double {
return exp(x)
}
// Find the base 10 exponential of x
// base10Exponential(x: 0) == 1
// base10Exponential(x: 1) == 10
func base10Exponential(x: Double) -> Double {
return pow(10, x)
}
// Find the base 2 exponential of x
// base2Exponential(x: 0) == 1
// base2Exponential(x: 1) == 2
func base2Exponential(x: Double) -> Double {
return pow(2
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
}
```
```swift
// Add
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
}
```
```swift
// Add
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
}
```
```swift
// Add
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
}
```
```swift
// Add
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
}
```
```swift
// Add
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
var s0 = s0.characters.sorted()
var s1 = s1.characters.sorted()
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
if s0[i] != s1[i] {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
var s0 = s0.characters.sorted()
var s1 = s1.characters.sorted()
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
if s0[i] != s1[i] {
return false
}
}
return true
}
```
var s0 = s0.characters.sorted() // 'characters' is unavailable: Please use String directly
var s0 = s0.characters.sorted() // invalid redeclaration of 's0'
var s1 = s1.characters.sorted() // invalid redeclaration of 's1'
var s1 = s1.characters.sorted() // 'characters' is unavailable: Please use String directly
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
var s0 = s0
var s1 = s1
var s0 = s0.map { $0 }
var s1 = s1.map { $0 }
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.sorted()
var s1 = s1.sorted()
var s0 = s0.map { String($0) }
var s1 = s1.map { String($0) }
var s0 = s0.joined()
var s1 = s1.joined()
var s
XCTAssertTrue(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "abcd", s1: "dddddddabc") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "dddddddabc", s1: "abcd") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "eabcd", s1: "dddddddabc") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "abcd", s1: "dddddddabcf") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "aabb", s1: "aaccc") == false) // cannot find 'sameChars' in scope
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.lowercased()
let s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lowercased()
var s1 = s1.lowercased()
var s0 = s0.lower
XCTAssertTrue(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "abcd", s1: "dddddddabc") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "dddddddabc", s1: "abcd") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "eabcd", s1: "dddddddabc") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "abcd", s1: "dddddddabcf") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "aabb", s1: "aaccc") == false) // cannot find 'sameChars' in scope
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.characters.count != s1.characters.count {
return false
}
for (index, _) in s0.characters.enumerate() {
let c0 = s0.characters.removeAtIndex(s0.startIndex)
let c1 = s1.characters.removeAtIndex(s1.startIndex)
if c0 != c1 {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.characters.count != s1.characters.count {
return false
}
for (index, _) in s0.characters.enumerate() {
let c0 = s0.characters.removeAtIndex(s0.startIndex)
let c1 = s1.characters.removeAtIndex(s1.startIndex)
if c0 != c1 {
return false
}
}
return true
}
```
if s0.characters.count != s1.characters.count { // 'characters' is unavailable: Please use String directly
if s0.characters.count != s1.characters.count { // 'characters' is unavailable: Please use String directly
for (index, _) in s0.characters.enumerate() { // value of type 'String' has no member 'enumerate'
let c0 = s0.characters.removeAtIndex(s0.startIndex) // value of type 'String' has no member 'removeAtIndex'
let c1 = s1.characters.removeAtIndex(s1.startIndex) // value of type 'String' has no member 'removeAtIndex'
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
let s0Char = s0[s0.index(s0.startIndex, offsetBy: i)]
let s1Char = s1[s1.index(s1.startIndex, offsetBy: i)]
if s0Char != s1Char {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
let s0Char = s0[s0.index(s0.startIndex, offsetBy: i)]
let s1Char = s1[s1.index(s1.startIndex, offsetBy: i)]
if s0Char != s1Char {
return false
}
}
return true
}
```
var s0 = s0 // variable 's0' was never mutated; consider changing to 'let' constant
var s1 = s1 // variable 's1' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.sorted()
let s1 = s1.sorted()
return s0 == s1
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = s0.sorted()
let s1 = s1.sorted()
return s0 == s1
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
let c0 = s0[s0.index(s0.startIndex, offsetBy: i)]
let c1 = s1[s1.index(s1.startIndex, offsetBy: i)]
if c0 != c1 {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
let c0 = s0[s0.index(s0.startIndex, offsetBy: i)]
let c1 = s1[s1.index(s1.startIndex, offsetBy: i)]
if c0 != c1 {
return false
}
}
return true
}
```
var s0 = s0 // variable 's0' was never mutated; consider changing to 'let' constant
var s1 = s1 // variable 's1' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
// Remove all whitespace
s0 = s0.replacingOccurrences(of: " ", with: "")
s1 = s1.replacingOccurrences(of: " ", with: "")
// Sort the strings
s0 = String(s0.sorted())
s1 = String(s1.sorted())
// Check if the strings are equal
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
// Remove all whitespace
s0 = s0.replacingOccurrences(of: " ", with: "")
s1 = s1.replacingOccurrences(of: " ", with: "")
// Sort the strings
s0 = String(s0.sorted())
s1 = String(s1.sorted())
// Check if the strings are equal
return s0 == s1
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.characters.count != s1.characters.count {
return false
}
while s0.characters.count > 0 {
let c0 = s0.characters.first!
let c1 = s1.characters.first!
if c0 != c1 {
return false
}
s0 = s0.substringFromIndex(s0.startIndex.successor())
s1 = s1.substringFromIndex(s1.startIndex.successor())
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
if s0.characters.count != s1.characters.count {
return false
}
while s0.characters.count > 0 {
let c0 = s0.characters.first!
let c1 = s1.characters.first!
if c0 != c1 {
return false
}
s0 = s0.substringFromIndex(s0.startIndex.successor())
s1 = s1.substringFromIndex(s1.startIndex.successor())
}
return true
}
```
if s0.characters.count != s1.characters.count { // 'characters' is unavailable: Please use String directly
if s0.characters.count != s1.characters.count { // 'characters' is unavailable: Please use String directly
while s0.characters.count > 0 { // 'characters' is unavailable: Please use String directly
let c0 = s0.characters.first! // 'characters' is unavailable: Please use String directly
let c1 = s1.characters.first! // 'characters' is unavailable: Please use String directly
s0 = s0.substringFromIndex(s0.startIndex.successor()) // value of type 'String' has no member 'substringFromIndex'
s0 = s0.substringFromIndex(s0.startIndex.successor()) // value of type 'String.Index' has no member 'successor'
s1 = s1.substringFromIndex(s1.startIndex.successor()) // value of type 'String.Index' has no member 'successor'
s1 = s1.substringFromIndex(s1.startIndex.successor()) // value of type 'String' has no member 'substringFromIndex'
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
// remove all characters from s0 that are not in s1
for c in s0 {
if !s1.contains(c) {
s0.remove(at: s0.index(of: c)!)
}
}
// remove all characters from s1 that are not in s0
for c in s1 {
if !s0.contains(c) {
s1.remove(at: s1.index(of: c)!)
}
}
return s0.isEmpty && s1.isEmpty
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
// remove all characters from s0 that are not in s1
for c in s0 {
if !s1.contains(c) {
s0.remove(at: s0.index(of: c)!)
}
}
// remove all characters from s1 that are not in s0
for c in s1 {
if !s0.contains(c) {
s1.remove(at: s1.index(of: c)!)
}
}
return s0.isEmpty && s1.isEmpty
}
```
s0.remove(at: s0.index(of: c)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
s1.remove(at: s1.index(of: c)!) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let t = a + b
a = b
b = t
}
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 t = a + b
a = b
b = t
}
return a
}
```
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let t = a
a = b
b = t + 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 {
let t = a
a = b
b = t + b
}
return a
}
```
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let tmp = a + b
a = b
b = tmp
}
return a
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let tmp = a + b
a = b
b = tmp
}
return a
}
```
func fib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```
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.popLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for 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 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 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
}
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 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 monotonic(l: [Int]) -> Bool {
let l = l.sorted()
let l2 = l.sorted(by: >)
return l == l2
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
let l = l.sorted()
let l2 = l.sorted(by: >)
return l == l2
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
var isIncreasing = false
var isDecreasing = false
for i in 0..<l.count - 1 {
if l[i] < l[i + 1] {
isIncreasing = true
} else if l[i] > l[i + 1] {
isDecreasing = true
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = false
var isDecreasing = false
for i in 0..<l.count - 1 {
if l[i] < l[i + 1] {
isIncreasing = true
} else if l[i] > l[i + 1] {
isDecreasing = true
}
}
return isIncreasing || isDecreasing
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
let l = l.sorted()
var i = 0
while i < l.count - 1 {
if l[i] == l[i + 1] {
i += 1
} else if l[i] < l[i + 1] {
return false
} else {
return true
}
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
let l = l.sorted()
var i = 0
while i < l.count - 1 {
if l[i] == l[i + 1] {
i += 1
} else if l[i] < l[i + 1] {
return false
} else {
return true
}
}
return true
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let isIncreasing = l.dropFirst().allSatisfy { $0 >= l.dropLast().first! }
let isDecreasing = l.dropFirst().allSatisfy { $0 <= l.dropLast().first! }
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let isIncreasing = l.dropFirst().allSatisfy { $0 >= l.dropLast().first! }
let isDecreasing = l.dropFirst().allSatisfy { $0 <= l.dropLast().first! }
return isIncreasing || isDecreasing
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
let l = l.sorted()
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
let l = l.sorted()
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let diff = l.dropFirst().map { $0 - l.dropLast().first! }
return diff.allSatisfy { $0 > 0 || $0 < 0 }
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
let diff = l.dropFirst().map { $0 - l.dropLast().first! }
return diff.allSatisfy { $0 > 0 || $0 < 0 }
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result: [Int] = []
// Sort both arrays.
l1.sort()
l2.sort()
// Find common elements.
var i1 = 0
var i2 = 0
while i1 < l1.count && i2 < l2.count {
if l1[i1] == l2[i2] {
result.append(l1[i1])
i1 += 1
i2 += 1
} else if l1[i1] < l2[i2] {
i1 += 1
} else {
i2 += 1
}
}
// Remove duplicates.
var result = Array(Set(result))
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result: [Int] = []
// Sort both arrays.
l1.sort()
l2.sort()
// Find common elements.
var i1 = 0
var i2 = 0
while i1 < l1.count && i2 < l2.count {
if l1[i1] == l2[i2] {
result.append(l1[i1])
i1 += 1
i2 += 1
} else if l1[i1] < l2[i2] {
i1 += 1
} else {
i2 += 1
}
}
// Remove duplicates.
var result = Array(Set(result))
return result
}
```
var result = Array(Set(result)) // invalid redeclaration of 'result'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result = [Int]()
// Sort the arrays.
l1.sort()
l2.sort()
// Find the common elements.
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
}
}
// Remove duplicates.
var unique = [Int]()
for num in result {
if !unique.contains(num) {
unique.append(num)
}
}
return unique
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result = [Int]()
// Sort the arrays.
l1.sort()
l2.sort()
// Find the common elements.
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
}
}
// Remove duplicates.
var unique = [Int]()
for num in result {
if !unique.contains(num) {
unique.append(num)
}
}
return unique
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result: [Int] = []
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] {
l2.removeFirst()
} else {
l1.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 l1 = l1
var l2 = l2
var result: [Int] = []
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] {
l2.removeFirst()
} else {
l1.removeFirst()
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result: [Int] = []
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] {
l2.removeFirst()
} else {
l1.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 l1 = l1
var l2 = l2
var result: [Int] = []
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] {
l2.removeFirst()
} else {
l1.removeFirst()
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result = [Int]()
while l1.count > 0 && l2.count > 0 {
if l1[0] == l2[0] {
result.append(l1[0])
l1.remove(at: 0)
l2.remove(at: 0)
} else if l1[0] > l2[0] {
l2.remove(at: 0)
} else {
l1.remove(at: 0)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result = [Int]()
while l1.count > 0 && l2.count > 0 {
if l1[0] == l2[0] {
result.append(l1[0])
l1.remove(at: 0)
l2.remove(at: 0)
} else if l1[0] > l2[0] {
l2.remove(at: 0)
} else {
l1.remove(at: 0)
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result: [Int] = []
// Sort the arrays
l1.sort()
l2.sort()
// Loop through the first array
for i in 0..<l1.count {
// Loop through the second array
for j in 0..<l2.count {
// If the elements are equal
if l1[i] == l2[j] {
// Add the element to the result array
result.append(l1[i])
// Remove the element from the second array
l2.remove(at: j)
break
}
}
}
// Return the result array
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result: [Int] = []
// Sort the arrays
l1.sort()
l2.sort()
// Loop through the first array
for i in 0..<l1.count {
// Loop through the second array
for j in 0..<l2.count {
// If the elements are equal
if l1[i] == l2[j] {
// Add the element to the result array
result.append(l1[i])
// Remove the element from the second array
l2.remove(at: j)
break
}
}
}
// Return the result array
return result
}
// Test the function
print(common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]))
print(common(l1: [5, 3, 2, 8], l2: [3, 2]))
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result = [Int]()
// Sort both arrays
l1.sort()
l2.sort()
// Find common elements
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
}
}
// Remove duplicates
var unique = [Int]()
for num in result {
if !unique.contains(num) {
unique.append(num)
}
}
return unique
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
var result = [Int]()
// Sort both arrays
l1.sort()
l2.sort()
// Find common elements
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
}
}
// Remove duplicates
var unique = [Int]()
for num in result {
if !unique.contains(num) {
unique.append(num)
}
}
return unique
}
// Test
print(common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]))
print(common(l1: [5, 3, 2, 8], l2: [3, 2]))
```
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var factors = [Int]()
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```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 factors = [Int]()
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var factors = [Int]()
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```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 factors = [Int]()
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var largest = 1
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return max(largest, n)
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var largest = 1
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return max(largest, n)
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var factors = [Int]()
var factor = n
while factor > 1 {
if factor % i == 0 {
factors.append(i)
factor /= i
} else {
i += 1
}
}
return factors.max()!
}
```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 factors = [Int]()
var factor = n
while factor > 1 {
if factor % i == 0 {
factors.append(i)
factor /= i
} else {
i += 1
}
}
return factors.max()!
}
```
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var result = 0
while i <= n {
if n % i == 0 {
result = i
n = n / i
} else {
i += 1
}
}
return result
}
```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 result = 0
while i <= n {
if n % i == 0 {
result = i
n = n / i
} else {
i += 1
}
}
return result
}
```
n = n / i // cannot assign to value: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var factors = [Int]()
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```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 factors = [Int]()
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var largestFactor = 1
while i * i <= n {
if n % i == 0 {
largestFactor = i
n /= i
} else {
i += 1
}
}
return n > 1 ? n : largestFactor
}
```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 largestFactor = 1
while i * i <= n {
if n % i == 0 {
largestFactor = i
n /= i
} else {
i += 1
}
}
return n > 1 ? n : largestFactor
}
```
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 {
return largestPrimeFactor(n: 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 {
if n % i == 0 {
return largestPrimeFactor(n: n / i)
}
i += 1
}
return n
}
```
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var factors: [Int] = []
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```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 factors: [Int] = []
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
factors.append(n)
return factors.max()!
}
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var factors: [Int] = []
var n = n
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
if n > 1 {
factors.append(n)
}
return factors.max()!
}
```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 factors: [Int] = []
var n = n
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
if n > 1 {
factors.append(n)
}
return factors.max()!
}
```
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
}
func sumToN2(n: Int) -> Int {
return (1...n).reduce(0, +)
}
func sumToN3(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
func sumToN4(n: Int) -> Int {
return (1...n).reduce(0, { (sum, i) in sum + i })
}
func sumToN5(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
func sumToN6(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
func sumToN7(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
func sumToN8(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
// sum_to_n_2 is a function that sums numbers from 1 to n.
// sumToN2(n: 30) == 465
// sumToN2(n: 100) == 5050
// sumToN2(n: 5) == 15
// sumToN2(n: 10) == 55
// sumToN2(n: 1) == 1
func sumToN2(n: Int) -> Int {
return (1...n).reduce(0, +)
}
// sum_to_n_3 is a function that sums numbers from 1 to n.
// sumToN3(n: 30) == 465
// sumToN3(n: 100) == 5050
// sumToN3(n: 5) == 15
// sumToN3(n: 10) == 55
// sumToN3(n: 1) == 1
func sumToN3(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
// sum_to_n_4 is a function that sums numbers from 1 to n.
// sumToN4(n: 30) == 465
// sumToN4(n: 100) == 5050
// sumToN4(n: 5) == 15
// sumToN4(n: 10) == 55
// sumToN4(n: 1) == 1
func sumToN4(n: Int) -> Int {
return (1...n).reduce(0, { (sum, i) in sum + i })
}
// sum_to_n_5 is a function that sums numbers from 1 to n.
// sumToN5(n: 30) == 465
// sumToN5(n: 100) == 5050
// sumToN5(n: 5) == 15
// sumToN5(n: 10) == 55
// sumToN5(n: 1) == 1
func sumToN5(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
// sum_to_n_6 is a function that sums numbers from 1 to n.
// sumToN6(n: 30) == 465
// sumToN6(n: 100) == 5050
// sumToN6(n: 5) == 15
// sumToN6(n: 10) == 55
// sumToN6(n: 1) == 1
func sumToN6(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
// sum_to_n_7 is a function that sums numbers from 1 to n.
// sumToN7(n: 30) == 465
// sumToN7(n: 100) == 5050
// sumToN7(n: 5) == 15
// sumToN7(n: 10) == 55
// sumToN7(n: 1) == 1
func sumToN7(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
// sum_to_n_8 is a function that sums numbers from 1 to n.
// sumToN8(n: 30) == 465
// sumToN8(n: 100) == 5050
// sumToN8(n: 5) == 15
// sumToN8(n: 10) == 55
// sumToN8(n: 1) == 1
func sumToN8(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for 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
} 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
}
stack.popLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for 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 char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for 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 derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(0)
} else {
result.append(xs[i] * i)
}
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(0)
} else {
result.append(xs[i] * i)
}
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
result.append(0)
} else {
result.append(xs[i] * i)
}
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
result.append(0)
} else {
result.append(xs[i] * i)
}
}
return result
}
```
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result: [Int] = []
for i in 0..<xs.count {
if i == 0 {
continue
}
result.append(xs[i] * i)
}
return result
}
```
func fibfib(n: Int) -> Int {
if n < 0 {
return 0
}
var fibfib = [0, 0, 1]
for i in 3...n {
fibfib.append(fibfib[i-1] + fibfib[i-2] + fibfib[i-3])
}
return fibfib[n]
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n < 0 {
return 0
}
var fibfib = [0, 0, 1]
for i in 3...n {
fibfib.append(fibfib[i-1] + fibfib[i-2] + fibfib[i-3])
}
return fibfib[n]
}
print(fibfib(n: 1))
print(fibfib(n: 5))
print(fibfib(n: 8))
```
// Fatal error: Range requires lowerBound <= upperBound
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fib = [0, 0, 1]
for i in 3...n {
fib.append(fib[i-1] + fib[i-2] + fib[i-3])
}
return fib[n]
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fib = [0, 0, 1]
for i in 3...n {
fib.append(fib[i-1] + fib[i-2] + fib[i-3])
}
return fib[n]
}
}
```
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fibfib1 = 0
var fibfib2 = 0
var fibfib3 = 1
var fibfibN = 0
for _ in 0..<n {
fibfibN = fibfib1 + fibfib2 + fibfib3
fibfib1 = fibfib2
fibfib2 = fibfib3
fibfib3 = fibfibN
}
return fibfibN
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fibfib1 = 0
var fibfib2 = 0
var fibfib3 = 1
var fibfibN = 0
for _ in 0..<n {
fibfibN = fibfib1 + fibfib2 + fibfib3
fibfib1 = fibfib2
fibfib2 = fibfib3
fibfib3 = fibfibN
}
return fibfibN
}
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
}
if n == 3 {
return 1
}
var fibfibArray = [0, 0, 1]
for i in 3...n {
fibfibArray.append(fibfibArray[i-1] + fibfibArray[i-2] + fibfibArray[i-3])
}
return fibfibArray[n]
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
}
if n == 3 {
return 1
}
var fibfibArray = [0, 0, 1]
for i in 3...n {
fibfibArray.append(fibfibArray[i-1] + fibfibArray[i-2] + fibfibArray[i-3])
}
return fibfibArray[n]
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fib = [0, 0, 1]
for i in 3...n {
fib.append(fib[i-1] + fib[i-2] + fib[i-3])
}
return fib[n]
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fib = [0, 0, 1]
for i in 3...n {
fib.append(fib[i-1] + fib[i-2] + fib[i-3])
}
return fib[n]
}
}
```
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
} else if n == 3 {
return 1
} else {
var fib1 = 0
var fib2 = 0
var fib3 = 1
var fib = 0
for _ in 3...n {
fib = fib1 + fib2 + fib3
fib1 = fib2
fib2 = fib3
fib3 = fib
}
return fib
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
} else if n == 3 {
return 1
} else {
var fib1 = 0
var fib2 = 0
var fib3 = 1
var fib = 0
for _ in 3...n {
fib = fib1 + fib2 + fib3
fib1 = fib2
fib2 = fib3
fib3 = fib
}
return fib
}
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n < 0 {
return 0
}
if n < 3 {
return n
}
var fibfib = [0, 0, 1]
for i in 3...n {
fibfib.append(fibfib[i-1] + fibfib[i-2] + fibfib[i-3])
}
return fibfib[n]
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n < 0 {
return 0
}
if n < 3 {
return n
}
var fibfib = [0, 0, 1]
for i in 3...n {
fibfib.append(fibfib[i-1] + fibfib[i-2] + fibfib[i-3])
}
return fibfib[n]
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
} else if n == 3 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n <= 2 {
return 0
} else if n == 3 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
}
if n == 2 {
return 1
}
var fibfibArray = [0, 0, 1]
for i in 3...n {
fibfibArray.append(fibfibArray[i-1] + fibfibArray[i-2] + fibfibArray[i-3])
}
return fibfibArray[n]
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
}
if n == 2 {
return 1
}
var fibfibArray = [0, 0, 1]
for i in 3...n {
fibfibArray.append(fibfibArray[i-1] + fibfibArray[i-2] + fibfibArray[i-3])
}
return fibfibArray[n]
}
```
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
}
if n == 2 {
return 1
}
var fibfib = [0, 0, 1]
for i in 3...n {
fibfib.append(fibfib[i-1] + fibfib[i-2] + fibfib[i-3])
}
return fibfib[n]
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 || n == 1 {
return 0
}
if n == 2 {
return 1
}
var fibfib = [0, 0, 1]
for i in 3...n {
fibfib.append(fibfib[i-1] + fibfib[i-2] + fibfib[i-3])
}
return fibfib[n]
}
```
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let digitsCount = digits.count
if shift > digitsCount {
return digits.reversed().map { String($0) }.joined()
}
let shiftedDigits = digits.dropFirst(digitsCount - shift) + digits.prefix(digitsCount - shift)
return 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).characters.map { Int(String($0))! }
let digitsCount = digits.count
if shift > digitsCount {
return digits.reversed().map { String($0) }.joined()
}
let shiftedDigits = digits.dropFirst(digitsCount - shift) + digits.prefix(digitsCount - shift)
return shiftedDigits.map { String($0) }.joined()
}
```
let digits = String(x).characters.map { Int(String($0))! } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let digitsCount = digits.count
let shiftCount = shift % digitsCount
if shiftCount == 0 {
return String(digits)
}
let shiftedDigits = Array(digits[digitsCount - shiftCount..<digitsCount]) + Array(digits[0..<digitsCount - shiftCount])
return String(shiftedDigits)
}
```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 digitsCount = digits.count
let shiftCount = shift % digitsCount
if shiftCount == 0 {
return String(digits)
}
let shiftedDigits = Array(digits[digitsCount - shiftCount..<digitsCount]) + Array(digits[0..<digitsCount - shiftCount])
return String(shiftedDigits)
}
```
return String(digits) // no exact matches in call to initializer
return String(shiftedDigits) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let numberOfDigits = digits.count
if shift > numberOfDigits {
return digits.reversed().joined()
}
let shiftedDigits = digits.dropFirst(numberOfDigits - shift) + digits.prefix(numberOfDigits - shift)
return shiftedDigits.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let numberOfDigits = digits.count
if shift > numberOfDigits {
return digits.reversed().joined()
}
let shiftedDigits = digits.dropFirst(numberOfDigits - shift) + digits.prefix(numberOfDigits - shift)
return shiftedDigits.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let count = digits.count
let shift = shift % count
let shifted = zip(digits.dropLast(shift), digits.dropFirst(count - shift)).map { $0 + $1 }
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).characters.map { Int(String($0))! }
let count = digits.count
let shift = shift % count
let shifted = zip(digits.dropLast(shift), digits.dropFirst(count - shift)).map { $0 + $1 }
return String(shifted.reversed())
}
```
let digits = String(x).characters.map { Int(String($0))! } // 'characters' is unavailable: Please use String directly
return String(shifted.reversed()) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let numberOfDigits = digits.count
if shift > numberOfDigits {
return digits.reversed().joined()
}
let shiftedDigits = digits.dropFirst(numberOfDigits - shift) + digits.prefix(numberOfDigits - shift)
return shiftedDigits.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let numberOfDigits = digits.count
if shift > numberOfDigits {
return digits.reversed().joined()
}
let shiftedDigits = digits.dropFirst(numberOfDigits - shift) + digits.prefix(numberOfDigits - shift)
return shiftedDigits.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let shift = shift % digits.count
let result = digits.dropLast(shift).reversed() + digits.suffix(shift)
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { Int(String($0))! }
let shift = shift % digits.count
let result = digits.dropLast(shift).reversed() + digits.suffix(shift)
return String(result)
}
```
let digits = String(x).characters.map { Int(String($0))! } // 'characters' is unavailable: Please use String directly
return String(result) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let shift = shift % digits.count
let shifted = digits.dropLast(shift).append(contentsOf: digits.dropFirst(digits.count - shift))
return shifted.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters.map { String($0) }
let shift = shift % digits.count
let shifted = digits.dropLast(shift).append(contentsOf: digits.dropFirst(digits.count - shift))
return shifted.joined()
}
```
let digits = String(x).characters.map { String($0) } // 'characters' is unavailable: Please use String directly
let shifted = digits.dropLast(shift).append(contentsOf: digits.dropFirst(digits.count - shift)) // cannot use mutating member on immutable value: function call returns immutable value
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
if shift > digits.count {
return digits.reversed().joined()
}
let shifted = digits.dropFirst(shift) + digits.prefix(shift)
return shifted.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
if shift > digits.count {
return digits.reversed().joined()
}
let shifted = digits.dropFirst(shift) + digits.prefix(shift)
return shifted.joined()
}
// circularShift(x: 12, shift: 1)
// circularShift(x: 12, shift: 2)
// circularShift(x: 12, shift: 3)
// circularShift(x: 12, shift: 4)
// circularShift(x: 12, shift: 5)
// circularShift(x: 12, shift: 6)
// circularShift(x: 12, shift: 7)
// circularShift(x: 12, shift: 8)
// circularShift(x: 12, shift: 9)
// circularShift(x: 12, shift: 10)
// circularShift(x: 12, shift: 11)
// circularShift(x: 12, shift: 12)
// circularShift(x: 12, shift: 13)
// circularShift(x: 12, shift: 14)
// circularShift(x: 12, shift: 15)
// circularShift(x: 12, shift: 16)
// circularShift(x: 12, shift: 17)
// circularShift(x: 12, shift: 18)
// circularShift(x: 12, shift: 19)
// circularShift(x: 12, shift: 20)
// circularShift(x: 12, shift: 21)
// circularShift(x: 12, shift: 22)
// circularShift(x: 12, shift: 23)
// circularShift(x: 12, shift: 24)
// circularShift(x: 12, shift: 25)
// circularShift(x: 12, shift: 26)
// circularShift(x: 12, shift: 27)
// circularShift(x: 12, shift: 28)
// circularShift(x: 12, shift: 29)
// circularShift(x: 12, shift: 30)
// circularShift(x: 12, shift: 31)
// circularShift(x: 12, shift: 32)
// circularShift(x: 12, shift: 33)
// circularShift(x: 12, shift: 34)
// circularShift(x: 12, shift: 35)
// circularShift(x: 12, shift: 36)
// circularShift(x: 12, shift: 37)
// circularShift(x: 12, shift: 38)
// circularShift(x: 12, shift: 39)
// circularShift(x: 12, shift: 40)
// circularShift(x: 12, shift: 41)
// circularShift(x: 12, shift: 42)
// circularShift(x: 12, shift: 43)
// circularShift(x: 12, shift: 44)
// circularShift(x: 12, shift: 45)
// circularShift(x: 12, shift: 46)
// circularShift(x: 12, shift: 47)
// circularShift(x: 12, shift: 48)
// circularShift(x: 12, shift: 49)
// circularShift(x: 12, shift: 50)
// circularShift(x: 12, shift: 51)
// circularShift(x: 12, shift: 52)
// circularShift(x: 12, shift: 53)
// circularShift(x: 12, shift: 54)
// circularShift(x: 12, shift: 55)
// circularShift(x: 12, shift: 56)
// circularShift(x: 12, shift: 57
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
let shift = shift % digits.count
let reversed = digits.reversed()
let shifted = Array(reversed[0..<shift]) + Array(reversed[shift..<digits.count])
return shifted.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { String($0) }
let shift = shift % digits.count
let reversed = digits.reversed()
let shifted = Array(reversed[0..<shift]) + Array(reversed[shift..<digits.count])
return shifted.joined()
}
```
let shifted = Array(reversed[0..<shift]) + Array(reversed[shift..<digits.count]) // subscript 'subscript(_:)' requires the types 'ReversedCollection<[String]>.Index' and 'Int' be equivalent
let shifted = Array(reversed[0..<shift]) + Array(reversed[shift..<digits.count]) // subscript 'subscript(_:)' requires the types 'ReversedCollection<[String]>.Index' and 'Int' be equivalent
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shift = shift % digits.count
let shifted = Array(digits.dropFirst(shift) + digits.prefix(shift))
return shifted.map { String($0) }.joined()
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shift = shift % digits.count
let shifted = Array(digits.dropFirst(shift) + digits.prefix(shift))
return shifted.map { String($0) }.joined()
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if let asciiValue = char.asciiValue {
if asciiValue >= 65 && asciiValue <= 90 {
sum += Int(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 let asciiValue = char.asciiValue {
if asciiValue >= 65 && asciiValue <= 90 {
sum += Int(asciiValue)
}
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char >= "A" && char <= "Z" {
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 >= "A" && char <= "Z" {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
```
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruit = s.components(separatedBy: " ")
let apples = Int(fruit[0])!
let oranges = Int(fruit[2])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruit = s.components(separatedBy: " ")
let apples = Int(fruit[0])!
let oranges = Int(fruit[2])!
let mango = n - apples - oranges
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let s = s.components(separatedBy: " ")
let apples = Int(s[0])!
let oranges = Int(s[2])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let s = s.components(separatedBy: " ")
let apples = Int(s[0])!
let oranges = Int(s[2])!
return n - apples - oranges
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let s = s.components(separatedBy: " ")
let apples = Int(s[0])!
let oranges = Int(s[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let s = s.components(separatedBy: " ")
let apples = Int(s[0])!
let oranges = Int(s[2])!
let mangoes = n - (apples + oranges)
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let count = s.split(separator: " ").map { Int($0) ?? 0 }
return n - (count[0] + count[1])
}
```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 count = s.split(separator: " ").map { Int($0) ?? 0 }
return n - (count[0] + count[1])
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
return n - apples - oranges
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.split(separator: " ")
let apples = Int(fruits[0])!
let oranges = Int(fruits[2])!
let mangoes = n - apples - oranges
return mangoes
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEvenValue, smallestIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEvenValue, smallestIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEvenValue, smallestIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEvenValue, smallestIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEvenValue, smallestIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEvenValue, smallestIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestEvenIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEven {
smallestEven = value
smallestEvenIndex = index
}
}
return smallestEvenIndex == -1 ? [] : [smallestEven, smallestEvenIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestEvenIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEven {
smallestEven = value
smallestEvenIndex = index
}
}
return smallestEvenIndex == -1 ? [] : [smallestEven, smallestEvenIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEven {
smallestEven = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEven, smallestIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEven {
smallestEven = value
smallestIndex = index
}
}
return smallestIndex == -1 ? [] : [smallestEven, smallestIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = Int.max
var smallestEvenValueIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < smallestEvenValue {
smallestEvenValue = value
smallestEvenValueIndex = index
}
}
return smallestEvenValueIndex == -1 ? [] : [smallestEvenValue, smallestEvenValueIndex]
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if let count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
for (key, value) in dict {
if 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 count = dict[i] {
dict[i] = count + 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 {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
if let count = dict[num] {
dict[num] = count + 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 count = dict[num] {
dict[num] = count + 1
} else {
dict[num] = 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 {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
if let count = dict[i] {
dict[i] = count + 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 count = dict[i] {
dict[i] = count + 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 i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for num in lst {
dict[num] = (dict[num] ?? 0) + 1
}
for (key, value) in dict {
if value >= key {
return key
}
}
return -1
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var result = [Int]()
var sortedList = lst.sorted()
while sortedList.count > 0 {
result.append(sortedList.removeFirst())
result.append(sortedList.removeLast())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var result = [Int]()
var sortedList = lst.sorted()
while sortedList.count > 0 {
result.append(sortedList.removeFirst())
result.append(sortedList.removeLast())
}
return result
}
```
// Fatal error: Can't remove last element from an empty collection
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
var j = sorted.count - 1
while i <= j {
if i == j {
result.append(sorted[i])
break
}
result.append(sorted[i])
result.append(sorted[j])
i += 1
j -= 1
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
var j = sorted.count - 1
while i <= j {
if i == j {
result.append(sorted[i])
break
}
result.append(sorted[i])
result.append(sorted[j])
i += 1
j -= 1
}
return result
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```
func strangeSortList(lst: [Int]) -> [Int] {
var newList = lst
var sortedList = [Int]()
while newList.count > 0 {
let min = newList.min()!
let max = newList.max()!
newList.remove(at: newList.firstIndex(of: min)!)
newList.remove(at: newList.firstIndex(of: max)!)
sortedList.append(min)
sortedList.append(max)
}
return sortedList
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var newList = lst
var sortedList = [Int]()
while newList.count > 0 {
let min = newList.min()!
let max = newList.max()!
newList.remove(at: newList.firstIndex(of: min)!)
newList.remove(at: newList.firstIndex(of: max)!)
sortedList.append(min)
sortedList.append(max)
}
return sortedList
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
var j = sorted.count - 1
while i <= j {
result.append(sorted[i])
i += 1
if i <= j {
result.append(sorted[j])
j -= 1
}
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
var j = sorted.count - 1
while i <= j {
result.append(sorted[i])
i += 1
if i <= j {
result.append(sorted[j])
j -= 1
}
}
return result
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```
var i = 0 // initialization of variable 'i' was never used; consider replacing with assignment to '_' or removing it
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
var j = sorted.count - 1
while i <= j {
if i == j {
result.append(sorted[i])
break
}
result.append(sorted[i])
result.append(sorted[j])
i += 1
j -= 1
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = [Int]()
var sorted = lst.sorted()
var i = 0
var j = sorted.count - 1
while i <= j {
if i == j {
result.append(sorted[i])
break
}
result.append(sorted[i])
result.append(sorted[j])
i += 1
j -= 1
}
return result
}
```
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList = lst.sorted()
var newList = [Int]()
while sortedList.count > 0 {
newList.append(sortedList.removeFirst())
if sortedList.count > 0 {
newList.append(sortedList.removeLast())
}
}
return newList
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var sortedList = lst.sorted()
var newList = [Int]()
while sortedList.count > 0 {
newList.append(sortedList.removeFirst())
if sortedList.count > 0 {
newList.append(sortedList.removeLast())
}
}
return newList
}
```
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sorted = [Int]()
var remaining = lst
while remaining.count > 0 {
let min = remaining.min()!
let max = remaining.max()!
sorted.append(min)
sorted.append(max)
remaining = remaining.filter { $0 != min && $0 != max }
}
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] {
guard lst.count > 1 else { return lst }
var sorted = [Int]()
var remaining = lst
while remaining.count > 0 {
let min = remaining.min()!
let max = remaining.max()!
sorted.append(min)
sorted.append(max)
remaining = remaining.filter { $0 != min && $0 != max }
}
return sorted
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var sorted = lst.sorted()
var result = [Int]()
while sorted.count > 0 {
result.append(sorted.removeFirst())
if sorted.count > 0 {
result.append(sorted.removeLast())
}
}
return result
}
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c) / 2)
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
return area
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c) / 2)
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
return area
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (Double(a) + Double(b) + Double(c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (Double(a) + Double(b) + Double(c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
return area
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
return area
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s) * (Double(s) - Double(a)) * (Double(s) - Double(b)) * (Double(s) - Double(c)))
if a + b > c && a + c > b && b + c > a {
return round(area * 100) / 100
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s) * (Double(s) - Double(a)) * (Double(s) - Double(b)) * (Double(s) - Double(c)))
if a + b > c && a + c > b && b + c > a {
return round(area * 100) / 100
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c)) / 2
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s) * (Double(s) - Double(a)) * (Double(s) - Double(b)) * (Double(s) - Double(c)))
return area
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(Double(s) * (Double(s) - Double(a)) * (Double(s) - Double(b)) * (Double(s) - Double(c)))
return area
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c) / 2)
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
return area
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = Double((a + b + c) / 2)
let area = sqrt(s * (s - Double(a)) * (s - Double(b)) * (s - Double(c)))
return area
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2.0
let area = sqrt(s * (s - a) * (s - b) * (s - c))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2.0
let area = sqrt(s * (s - a) * (s - b) * (s - c))
if a + b > c && a + c > b && b + c > a {
return area
} else {
return -1
}
}
```
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
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
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w {
return false
}
let isPalindrome = q.reversed() == q
return isPalindrome
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w {
return false
}
let isPalindrome = q.reversed() == q
return isPalindrome
}
```
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q = q.reversed()
let q = q.sorted()
let q =
XCTAssertTrue(willItFly(q: [3, 2, 3], w: 9) == true) // cannot find 'willItFly' in scope
XCTAssertTrue(willItFly(q: [1, 2], w: 5) == false) // cannot find 'willItFly' in scope
XCTAssertTrue(willItFly(q: [3], w: 5) == true) // cannot find 'willItFly' in scope
XCTAssertTrue(willItFly(q: [3, 2, 3], w: 1) == false) // cannot find 'willItFly' in scope
XCTAssertTrue(willItFly(q: [1, 2, 3], w: 6) == false) // cannot find 'willItFly' in scope
XCTAssertTrue(willItFly(q: [5], w: 5) == true) // cannot find 'willItFly' in scope
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
let q = q.sorted()
let q = q.reversed()
for i in 0..<q.count {
if q[i] != q[q.count - 1 - i] {
return false
}
}
return true
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
let q = q.sorted()
let q = q.reversed()
for i in 0..<q.count {
if q[i] != q[q.count - 1 - i] {
return false
}
}
return true
}
return false
}
```
let q = q.reversed() // invalid redeclaration of 'q'
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
return true
}
let count = q.count
for i in 0..<count {
var left = 0
var right = 0
for j in 0..<i {
left += q[j]
}
for j in i..<count {
right += q[j]
}
if left == right {
return true
}
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
return true
}
let count = q.count
for i in 0..<count {
var left = 0
var right = 0
for j in 0..<i {
left += q[j]
}
for j in i..<count {
right += q[j]
}
if left == right {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
let isPalindromic = q == q.reversed()
return isPalindromic
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w {
let isPalindromic = q == q.reversed()
return isPalindromic
}
return false
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w && q == q.reversed() {
return true
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum <= w && q == q.reversed() {
return true
}
return false
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let isBalanced = q == q.reversed()
return sum <= w && isBalanced
}
```
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum <= w && q == q.reversed() {
return true
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum <= w && q == q.reversed() {
return true
}
return false
}
```
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[j] = arr[i]
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[j] = arr[i]
}
i += 1
j -= 1
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var arr = arr
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var arr = arr
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[j] = arr[i]
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[j] = arr[i]
}
i += 1
j -= 1
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var arr = arr
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var arr = arr
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var arr = arr
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var arr = arr
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
arr[i] = arr[j]
}
i += 1
j -= 1
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count / 2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
arr[i] = arr[arr.count - 1 - i]
}
}
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 arr = arr
for i in 0..<arr.count / 2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
arr[i] = arr[arr.count - 1 - i]
}
}
return count
}
```
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - i - 1] {
count += 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 arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - i - 1] {
count += 1
}
}
return count
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count-i-1] {
count += 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 arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count-i-1] {
count += 1
}
}
return count
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 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 arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
if arr[i] < arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var i = 0
var j = arr.count - 1
while i < j {
if arr[i] != arr[j] {
count += 1
if arr[i] < arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return count
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var count1 = 0
var count2 = 0
for i in lst1 {
count1 += i.count
}
for i in lst2 {
count2 += i.count
}
if count1 < count2 {
return lst1
} else if count1 > count2 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var count1 = 0
var count2 = 0
for i in lst1 {
count1 += i.count
}
for i in lst2 {
count2 += i.count
}
if count1 < count2 {
return lst1
} else if count1 > count2 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else {
return lst2
}
}
```
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else {
return lst2
}
}
```
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var lst1 = lst1
var lst2 = lst2
var count1 = 0
var count2 = 0
for i in lst1 {
count1 += i.count
}
for i in lst2 {
count2 += i.count
}
if count1 < count2 {
return lst1
} else if count1 > count2 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var lst1 = lst1
var lst2 = lst2
var count1 = 0
var count2 = 0
for i in lst1 {
count1 += i.count
}
for i in lst2 {
count2 += i.count
}
if count1 < count2 {
return lst1
} else if count1 > count2 {
return lst2
} else {
return lst1
}
}
```
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let total1 = lst1.reduce(0) { $0 + $1.count }
let total2 = lst2.reduce(0) { $0 + $1.count }
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let total1 = lst1.reduce(0) { $0 + $1.count }
let total2 = lst2.reduce(0) { $0 + $1.count }
if total1 < total2 {
return lst1
} else if total2 < total1 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total1 > total2 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else if total1 > total2 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total1 = 0
var total2 = 0
for i in lst1 {
total1 += i.count
}
for i in lst2 {
total2 += i.count
}
if total1 < total2 {
return lst1
} else {
return lst2
}
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
for i in 2..<a {
if a % i == 0 {
isPrime = true
}
}
return isPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
for i in 2..<a {
if a % i == 0 {
isPrime = true
}
}
return isPrime
}
print(isMultiplyPrime(a: 30))
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var isMultiplyPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 3 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var isMultiplyPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 3 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```
var isPrime = false // initialization of variable 'isPrime' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = true
var isMultiplyPrime = false
var count = 0
for i in 2...a {
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
count += 1
}
isPrime = true
}
if count % 3 == 0 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = true
var isMultiplyPrime = false
var count = 0
for i in 2...a {
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
count += 1
}
isPrime = true
}
if count % 3 == 0 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 3 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 3 {
isMultiplyPrime = true
}
return isMultiplyPrime
}
print(isMultiplyPrime(a: 30))
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
for i in 2...a {
if a % i == 0 {
isMultiplyPrime = true
}
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
for i in 2...a {
if a % i == 0 {
isMultiplyPrime = true
}
}
return isMultiplyPrime
}
print(isMultiplyPrime(a: 30))
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var i = 2
var j = 2
var k = 2
while i < a {
while j < a {
while k < a {
if i * j * k == a {
isMultiplyPrime = true
}
k += 1
}
j += 1
}
i += 1
}
return isMultiplyPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isMultiplyPrime = false
var i = 2
var j = 2
var k = 2
while i < a {
while j < a {
while k < a {
if i * j * k == a {
isMultiplyPrime = true
}
k += 1
}
j += 1
}
i += 1
}
return isMultiplyPrime
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
isPrime = true
}
return isPrime
}
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
for i in 2...a {
if a % i == 0 {
count += 1
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var i = 2
var count = 0
var result = false
while i < a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 2 {
result = true
}
return result
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var i = 2
var count = 0
var result = false
while i < a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 2 {
result = true
}
return result
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
for i in 2...a {
if a % i == 0 {
return true
}
}
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 {
for i in 2...a {
if a % i == 0 {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 3 {
isPrime = true
}
return isPrime
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var isPrime = false
var count = 0
var i = 2
while i <= a {
if a % i == 0 {
count += 1
i += 1
} else {
i += 1
}
}
if count == 3 {
isPrime = true
}
return isPrime
}
print(isMultiplyPrime(a: 30))
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x % n == 0
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x % n == 0
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
var result = false
var i = 0
while i <= x {
if Int(pow(Double(n), Double(i))) == x {
result = true
}
i += 1
}
return result
}
```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 {
var result = false
var i = 0
while i <= x {
if Int(pow(Double(n), Double(i))) == x {
result = true
}
i += 1
}
return result
}
```
// Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max
func isSimplePower(x: Int, n: Int) -> Bool {
var result = false
var i = 0
while i < x {
if n * i == x {
result = true
}
i += 1
}
return result
}
```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 {
var result = false
var i = 0
while i < x {
if n * i == x {
result = true
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
var result = false
var i = 0
while i < x {
if Int(pow(Double(n), Double(i))) == x {
result = true
}
i += 1
}
return result
}
```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 {
var result = false
var i = 0
while i < x {
if Int(pow(Double(n), Double(i))) == x {
result = true
}
i += 1
}
return result
}
```
// Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max
func isSimplePower(x: Int, n: Int) -> Bool {
var i = 0
var result = false
while i < x {
if Int(pow(Double(n), Double(i))) == x {
result = true
}
i += 1
}
return result
}
```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 {
var i = 0
var result = false
while i < x {
if Int(pow(Double(n), Double(i))) == x {
result = true
}
i += 1
}
return result
}
```
// Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x % n == 0 && isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x % n == 0 && isSimplePower(x: x / n, n: n)
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x % n == 0 && isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x % n == 0 && isSimplePower(x: x / n, n: n)
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
var result = false
var i = 0
while i < x {
if i == x {
result = true
}
i = i * n
}
return result
}
```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 {
var result = false
var i = 0
while i < x {
if i == x {
result = true
}
i = i * n
}
return result
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
var result = false
var i = 0
while i < x {
if i == x {
result = true
}
i = i * n
}
return result
}
```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 {
var result = false
var i = 0
while i < x {
if i == x {
result = true
}
i = i * n
}
return result
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
var i = 0
var result = false
while i < x {
if i == x {
result = true
}
i = i * n
}
return result
}
```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 {
var i = 0
var result = false
while i < x {
if i == x {
result = true
}
i = i * n
}
return result
}
```
func iscube(a: Int) -> Bool {
let cube = a.cubeRoot()
return cube * cube * cube == a
}
extension Int {
func cubeRoot() -> Int {
var guess = 1
var lastGuess = 0
while guess != lastGuess {
lastGuess = guess
guess = Int(Double(guess) * Double(guess) * Double(guess) / Double(a))
}
return guess
}
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.cubeRoot()
return cube * cube * cube == a
}
extension Int {
func cubeRoot() -> Int {
var guess = 1
var lastGuess = 0
while guess != lastGuess {
lastGuess = guess
guess = Int(Double(guess) * Double(guess) * Double(guess) / Double(a))
}
return guess
}
}
```
guess = Int(Double(guess) * Double(guess) * Double(guess) / Double(a)) // cannot find 'a' in scope
func iscube(a: Int) -> Bool {
let cube = a.isPerfectCube
return cube
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.isPerfectCube
return cube
}
```
let cube = a.isPerfectCube // value of type 'Int' has no member 'isPerfectCube'
func iscube(a: Int) -> Bool {
let cube = a.isCube()
return cube
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.isCube()
return cube
}
```
let cube = a.isCube() // value of type 'Int' has no member 'isCube'
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
var result = false
for i in 0...10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(iscube(a: 1) == true) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: 2) == false) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: -1) == true) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: 64) == true) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: 180) == false) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: 1000) == true) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: 0) == true) // cannot find 'iscube' in scope
XCTAssertTrue(iscube(a: 1729) == false) // cannot find 'iscube' in scope
func iscube(a: Int) -> Bool {
let cube = a.squareRoot()
return Int(cube) == cube
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.squareRoot()
return Int(cube) == cube
}
```
let cube = a.squareRoot() // value of type 'Int' has no member 'squareRoot'
func iscube(a: Int) -> Bool {
let cube = a.isCube
return cube
}
extension Int {
var isCube: Bool {
let cube = Int(pow(Double(self), 1/3))
return cube * cube * cube == self
}
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.isCube
return cube
}
extension Int {
var isCube: Bool {
let cube = Int(pow(Double(self), 1/3))
return cube * cube * cube == self
}
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
var i = 0
while i*i*i <= a {
if i*i*i == a {
return true
}
i += 1
}
return false
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
var i = 0
while i*i*i <= a {
if i*i*i == a {
return true
}
i += 1
}
return false
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
let cube = a.cubeRoot()
return cube * cube * cube == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.cubeRoot()
return cube * cube * cube == a
}
```
let cube = a.cubeRoot() // value of type 'Int' has no member 'cubeRoot'
func iscube(a: Int) -> Bool {
var cube = 0
var i = 0
while cube < a {
i += 1
cube = i*i*i
}
return cube == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
var cube = 0
var i = 0
while cube < a {
i += 1
cube = i*i*i
}
return cube == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
let cube = a.isCube
return cube
}
extension Int {
var isCube: Bool {
let cube = Int(pow(Double(self), 1/3))
return cube * cube * cube == self
}
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let cube = a.isCube
return cube
}
extension Int {
var isCube: Bool {
let cube = Int(pow(Double(self), 1/3))
return cube * cube * cube == self
}
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if i == "2" || i == "3" || i == "5" || i == "7" || i == "B" || i == "D" {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch char {
case "2", "3", "5", "7", "B", "D":
count += 1
default:
break
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! == 2 || digit! == 3 || digit! == 5 || digit! == 7 || digit! == 11 || digit! == 13) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! % 2 != 0 && digit! % 3 != 0 && digit! % 5 != 0 && digit! % 7 != 0 && digit! % 11 != 0 && digit! % 13 != 0) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let digit = Int(String(char), radix: 16)
if digit != nil && (digit! % 2 != 0 && digit! % 3 != 0 && digit! % 5 != 0 && digit! % 7 != 0 && digit! % 11 != 0 && digit! % 13 != 0) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let hexValue = Int(String(char), radix: 16)
if hexValue != nil && hexValue! > 1 && hexValue! % 2 != 0 && hexValue! % 3 != 0 && hexValue! % 5 != 0 && hexValue! % 7 != 0 {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
let hexValue = Int(String(char), radix: 16)
if hexValue != nil && hexValue! > 1 && hexValue! % 2 != 0 && hexValue! % 3 != 0 && hexValue! % 5 != 0 && hexValue! % 7 != 0 {
count += 1
}
}
return count
}
```
// 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 {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```
func decimalToBinary(decimal: Int) -> String {
var binary = ""
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 {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db\(binary)db"
}
```
func isHappy(s: String) -> Bool {
var count = 0
for i in 0..<s.count {
if i < s.count - 2 {
if s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i + 1)] {
count += 1
}
}
}
if count == 0 {
return true
}
return false
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var count = 0
for i in 0..<s.count {
if i < s.count - 2 {
if s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i + 1)] {
count += 1
}
}
}
if count == 0 {
return true
}
return false
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var count = 0
for i in 0..<s.count {
if i < s.count - 2 {
if s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i + 1)] {
count += 1
}
}
}
return count == 0
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var count = 0
for i in 0..<s.count {
if i < s.count - 2 {
if s[s.index(s.startIndex, offsetBy: i)] == s[s.index(s.startIndex, offsetBy: i + 1)] {
count += 1
}
}
}
return count == 0
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i] == chars[i+2] || chars[i+1] == chars[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i] == chars[i+2] || chars[i+1] == chars[i+2] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isHappy(s: String) -> Bool {
let chars = Array(s)
if chars.count < 3 {
return false
}
for i in 0..<chars.count - 2 {
if chars[i] == chars[i + 1] || chars[i] == chars[i + 2] || chars[i + 1] == chars[i + 2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
if chars.count < 3 {
return false
}
for i in 0..<chars.count - 2 {
if chars[i] == chars[i + 1] || chars[i] == chars[i + 2] || chars[i + 1] == chars[i + 2] {
return false
}
}
return true
}
```
func isHappy(s: String) -> Bool {
let s = Array(s)
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i] == s[i+2] || s[i+1] == s[i+2] {
return false
}
}
return true
}
```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 s = Array(s)
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i] == s[i+2] || s[i+1] == s[i+2] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isHappy(s: String) -> Bool {
let str = Array(s)
for i in 0..<str.count-2 {
if str[i] == str[i+1] || str[i] == str[i+2] || str[i+1] == str[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let str = Array(s)
for i in 0..<str.count-2 {
if str[i] == str[i+1] || str[i] == str[i+2] || str[i+1] == str[i+2] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i] == chars[i+2] || chars[i+1] == chars[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i] == chars[i+2] || chars[i+1] == chars[i+2] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i] == chars[i+2] || chars[i+1] == chars[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i] == chars[i+2] || chars[i+1] == chars[i+2] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i+1] == chars[i+2] || chars[i] == chars[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
for i in 0..<chars.count-2 {
if chars[i] == chars[i+1] || chars[i+1] == chars[i+2] || chars[i] == chars[i+2] {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isHappy(s: String) -> Bool {
let chars = Array(s)
if chars.count < 3 {
return false
}
for i in 0..<chars.count - 2 {
if chars[i] == chars[i + 1] || chars[i] == chars[i + 2] || chars[i + 1] == chars[i + 2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
if chars.count < 3 {
return false
}
for i in 0..<chars.count - 2 {
if chars[i] == chars[i + 1] || chars[i] == chars[i + 2] || chars[i + 1] == chars[i + 2] {
return false
}
}
return true
}
```
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 {
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 {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
var letterGrades = [String]()
for i in 0..<grades.count {
if grades[i] >= 4.0 {
letterGrades.append("A+")
} else if grades[i] >= 3.7 {
letterGrades.append("A")
} else if grades[i] >= 3.3 {
letterGrades.append("A-")
} else if grades[i] >= 3.0 {
letterGrades.append("B+")
} else if grades[i] >= 2.7 {
letterGrades.append("B")
} else if grades[i] >= 2.3 {
letterGrades.append("B-")
} else if grades[i] >= 2.0 {
letterGrades.append("C+")
} else if grades[i] >= 1.7 {
letterGrades.append("C")
} else if grades[i] >= 1.3 {
letterGrades.append("C-")
} else if grades[i] >= 1.0 {
letterGrades.append("D+")
} else if grades[i] >= 0.7 {
letterGrades.append("D")
} else if grades[i] >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
var letterGrades = [String]()
for i in 0..<grades.count {
if grades[i] >= 4.0 {
letterGrades.append("A+")
} else if grades[i] >= 3.7 {
letterGrades.append("A")
} else if grades[i] >= 3.3 {
letterGrades.append("A-")
} else if grades[i] >= 3.0 {
letterGrades.append("B+")
} else if grades[i] >= 2.7 {
letterGrades.append("B")
} else if grades[i] >= 2.3 {
letterGrades.append("B-")
} else if grades[i] >= 2.0 {
letterGrades.append("C+")
} else if grades[i] >= 1.7 {
letterGrades.append("C")
} else if grades[i] >= 1.3 {
letterGrades.append("C-")
} else if grades[i] >= 1.0 {
letterGrades.append("D+")
} else if grades[i] >= 0.7 {
letterGrades.append("D")
} else if grades[i] >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("E")
}
}
return letterGrades
}
```
var grades = grades // variable 'grades' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var 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 {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var 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 {
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 {
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 {
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 primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length <= 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let stringLength = string.count
if stringLength == 1 {
return false
}
for i in 2..<stringLength {
if stringLength % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let stringLength = string.count
if stringLength == 1 {
return false
}
for i in 2..<stringLength {
if stringLength % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// 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 stringLength = string.count
var isPrime = false
for i in 1...stringLength {
if stringLength % i == 0 {
isPrime = true
}
}
return 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 {
let stringLength = string.count
var isPrime = false
for i in 1...stringLength {
if stringLength % i == 0 {
isPrime = true
}
}
return isPrime
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return false
}
for i in 2..<length {
if length % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
let start = 10 * count
let end = 9 * count
return start + end
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
let start = 10 * count
let end = 9 * count
return start + end
}
print(startsOneEnds(n: 1))
print(startsOneEnds(n: 2))
print(startsOneEnds(n: 3))
print(startsOneEnds(n: 4))
print(startsOneEnds(n: 5))
print(startsOneEnds(n: 6))
print(startsOneEnds(n: 7))
print(startsOneEnds(n: 8))
print(startsOneEnds(n: 9))
print(startsOneEnds(n: 10))
print(startsOneEnds(n: 11))
print(startsOneEnds(n: 12))
print(startsOneEnds(n: 13))
print(startsOneEnds(n: 14))
print(startsOneEnds(n: 15))
print(startsOneEnds(n: 16))
print(startsOneEnds(n: 17))
print(startsOneEnds(n: 18))
print(startsOneEnds(n: 19))
print(startsOneEnds(n: 20))
print(startsOneEnds(n: 21))
print(startsOneEnds(n: 22))
print(startsOneEnds(n: 23))
print(startsOneEnds(n: 24))
print(startsOneEnds(n: 25))
print(startsOneEnds(n: 26))
print(startsOneEnds(n: 27))
print(startsOneEnds(n: 28))
print(startsOneEnds(n: 29))
print(startsOneEnds(n: 30))
print(startsOneEnds(n: 31))
print(startsOneEnds(n: 32))
print(startsOneEnds(n: 33))
print(startsOneEnds(n: 34))
print(startsOneEnds(n: 35))
print(startsOneEnds(n: 36))
print(startsOneEnds(n: 37))
print(startsOneEnds(n: 38))
print(startsOneEnds(n: 39))
print(startsOneEnds(n: 40))
print(startsOneEnds(n: 41))
print(startsOneEnds(n: 42))
print(startsOneEnds(n: 43))
print(startsOneEnds(n: 44))
print(startsOneEnds(n: 45))
print(startsOneEnds(n: 46))
print(startsOneEnds(n: 47))
print(startsOneEnds(n: 48))
print(startsOneEnds(n: 49))
print(startsOneEnds(n: 50))
print(startsOneEnds(n: 51))
print(startsOneEnds(n: 52))
print(startsOneEnds(n: 53))
print(startsOneEnds(n: 54))
print(startsOneEnds(n: 55))
print(startsOneEnds(n: 56))
print(startsOneEnds(n: 57))
print(startsOneEnds(n: 58))
print(startsOneEnds(n: 59))
print(startsOneEnds(n: 60))
print(startsOneEnds(n: 61))
print(startsOneEnds(n: 62))
print(startsOneEnds(n: 63))
print(startsOneEnds(n: 64))
print(startsOneEnds(n: 65))
print(startsOneEnds(n: 66))
print(startsOneEnds(n: 67))
print(startsOneEnds(n: 68))
print(startsOneEnds(n: 69))
print(startsOneEnds(n: 70))
print(startsOneEnds(n: 71))
print(startsOneEnds(n: 72))
print(startsOneEnds(n: 73))
print(startsOneEnds(n: 74))
print(startsOneEnds(n
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
let digits = Array(1...n)
let count = digits.reduce(1) {
$0 * 10
}
let start = 1
let end = 10
let startCount = (end - start) * (count - 1)
let endCount = (end - start) * (count - 1)
return startCount + endCount
}
```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 {
let digits = Array(1...n)
let count = digits.reduce(1) {
$0 * 10
}
let start = 1
let end = 10
let startCount = (end - start) * (count - 1)
let endCount = (end - start) * (count - 1)
return startCount + endCount
}
print(startsOneEnds(n: 2))
print(startsOneEnds(n: 3))
print(startsOneEnds(n: 4))
print(startsOneEnds(n: 5))
print(startsOneEnds(n: 6))
print(startsOneEnds(n: 7))
print(startsOneEnds(n: 8))
print(startsOneEnds(n: 9))
print(startsOneEnds(n: 10))
print(startsOneEnds(n: 11))
print(startsOneEnds(n: 12))
print(startsOneEnds(n: 13))
print(startsOneEnds(n: 14))
print(startsOneEnds(n: 15))
print(startsOneEnds(n: 16))
print(startsOneEnds(n: 17))
print(startsOneEnds(n: 18))
print(startsOneEnds(n: 19))
print(startsOneEnds(n: 20))
print(startsOneEnds(n: 21))
print(startsOneEnds(n: 22))
print(startsOneEnds(n: 23))
print(startsOneEnds(n: 24))
print(startsOneEnds(n: 25))
print(startsOneEnds(n: 26))
print(startsOneEnds(n: 27))
print(startsOneEnds(n: 28))
print(startsOneEnds(n: 29))
print(startsOneEnds(n: 30))
print(startsOneEnds(n: 31))
print(startsOneEnds(n: 32))
print(startsOneEnds(n: 33))
print(startsOneEnds(n: 34))
print(startsOneEnds(n: 35))
print(startsOneEnds(n: 36))
print(startsOneEnds(n: 37))
print(startsOneEnds(n: 38))
print(startsOneEnds(n: 39))
print(startsOneEnds(n: 40))
print(startsOneEnds(n: 41))
print(startsOneEnds(n: 42))
print(startsOneEnds(n: 43))
print(startsOneEnds(n: 44))
print(startsOneEnds(n: 45))
print(startsOneEnds(n: 46))
print(startsOneEnds(n: 47))
print(startsOneEnds(n: 48))
print(startsOneEnds(n: 49))
print(startsOneEnds(n: 50))
print(startsOneEnds(n: 51))
print(startsOneEnds(n: 52))
print(startsOneEnds(n: 53))
print(startsOneEnds(n: 54))
print(startsOneEnds(n: 55))
print(startsOneEnds(n: 56))
print(startsOneEnds(n: 57))
print(startsOneEnds(n: 58))
print(startsOneEnds(n: 59))
print(startsOneEnds(n: 60))
print(startsOneEnds(n: 61))
print(startsOneEnds(n: 62))
print(startsOneEnds(n: 63))
print(startsOneEnds(n: 64))
print(startsOneEnds(n: 65))
print(startsOneEnds(n: 66))
print(startsOneEnds(n: 67))
print(startsOneEnds(n: 68))
print(startsOneEnds(n: 69))
print(startsOneEnds(n: 70))
print(startsOneEnds(n: 71))
print(startsOneEnds(n: 72))
print(startsOneEnds(n: 73))
let count = digits.reduce(1) { // contextual closure type '(Int, Int) throws -> Int' expects 2 arguments, but 1 was used in closure body
return startCount + endCount // cannot convert return expression of type 'String' to return type 'Int'
func startsOneEnds(n: Int) -> Int {
if n == 0 {
return 0
}
let count = Int(pow(10, Double(n - 1)))
let start = Int(pow(10, Double(n - 1)))
let end = Int(pow(10, Double(n)))
return (end - start) + count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 0 {
return 0
}
let count = Int(pow(10, Double(n - 1)))
let start = Int(pow(10, Double(n - 1)))
let end = Int(pow(10, Double(n)))
return (end - start) + count
}
print(startsOneEnds(n: 1)) // 10
print(startsOneEnds(n: 2)) // 90
print(startsOneEnds(n: 3)) // 900
print(startsOneEnds(n: 4)) // 9000
print(startsOneEnds(n: 5)) // 90000
print(startsOneEnds(n: 6)) // 900000
print(startsOneEnds(n: 7)) // 9000000
print(startsOneEnds(n: 8)) // 90000000
print(startsOneEnds(n: 9)) // 900000000
print(startsOneEnds(n: 10)) // 9000000000
print(startsOneEnds(n: 11)) // 90000000000
print(startsOneEnds(n: 12)) // 900000000000
print(startsOneEnds(n: 13)) // 9000000000000
print(startsOneEnds(n: 14)) // 90000000000000
print(startsOneEnds(n: 15)) // 900000000000000
print(startsOneEnds(n: 16)) // 9000000000000000
print(startsOneEnds(n: 17)) // 90000000000000000
print(startsOneEnds(n: 18)) // 900000000000000000
print(startsOneEnds(n: 19)) // 9000000000000000000
print(startsOneEnds(n: 20)) // 90000000000000000000
print(startsOneEnds(n: 21)) // 900000000000000000000
print(startsOneEnds(n: 22)) // 9000000000000000000000
print(startsOneEnds(n: 23)) // 90000000000000000000000
print(startsOneEnds(n: 24)) // 900000000000000000000000
print(startsOneEnds(n: 25)) // 9000000000000000000000000
print(startsOneEnds(n: 26)) // 90000000000000000000000000
print(startsOneEnds(n: 27)) // 900000000000000000000000000
print(startsOneEnds(n: 28)) // 9000000000000000000000000000
print(startsOneEnds(n: 29)) // 90000000000000000000000000000
print(startsOneEnds(n: 30)) // 900000000000000000000000000000
print(startsOneEnds(n: 31)) // 9000000000000000
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let start = startsOneEnds(n: n - 1)
let end = startsOneEnds(n: n - 1)
return start + end
}
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let start = startsOneEndsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
func startsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let start = startsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
func endsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let start = startsOneEndsOne(n: n - 1)
let end = endsOne(n: n - 1)
return start + end
}
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOneEndsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
func startsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
func endsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOneEndsOne(n: n - 1)
let end = endsOne(n: n - 1)
return start + end
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let start = startsOneEnds(n: n - 1)
let end = startsOneEnds(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let start = startsOneEndsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1.
func startsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let start = startsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that end with 1.
func endsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let start = startsOneEndsOne(n: n - 1)
let end = endsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not start or end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOneEndsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not start with 1.
func startsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not end with 1.
func endsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOneEndsOne(n: n - 1)
let end = endsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not start or end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOneEndsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not start with 1.
func startsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOne(n: n - 1)
let end = startsOneEndsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not end with 1.
func endsOne(n: Int) -> Int {
if n == 1 {
return 0
}
let start = startsOneEndsOne(n: n - 1)
let end = endsOne(n: n - 1)
return start + end
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that do not start or end with 1.
func
func startsOneEndsOne(n: Int) -> Int { // invalid redeclaration of 'startsOneEndsOne(n:)'
func startsOne(n: Int) -> Int { // invalid redeclaration of 'startsOne(n:)'
func endsOne(n: Int) -> Int { // invalid redeclaration of 'endsOne(n:)'
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
let count1 = count + 10 * (count - 1)
let count2 = count1 + 9 * (count - 1)
return count2
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
let count1 = count + 10 * (count - 1)
let count2 = count1 + 9 * (count - 1)
return count2
}
print(startsOneEnds(n: 1))
print(startsOneEnds(n: 2))
print(startsOneEnds(n: 3))
print(startsOneEnds(n: 4))
print(startsOneEnds(n: 5))
print(startsOneEnds(n: 6))
print(startsOneEnds(n: 7))
print(startsOneEnds(n: 8))
print(startsOneEnds(n: 9))
print(startsOneEnds(n: 10))
print(startsOneEnds(n: 11))
print(startsOneEnds(n: 12))
print(startsOneEnds(n: 13))
print(startsOneEnds(n: 14))
print(startsOneEnds(n: 15))
print(startsOneEnds(n: 16))
print(startsOneEnds(n: 17))
print(startsOneEnds(n: 18))
print(startsOneEnds(n: 19))
print(startsOneEnds(n: 20))
print(startsOneEnds(n: 21))
print(startsOneEnds(n: 22))
print(startsOneEnds(n: 23))
print(startsOneEnds(n: 24))
print(startsOneEnds(n: 25))
print(startsOneEnds(n: 26))
print(startsOneEnds(n: 27))
print(startsOneEnds(n: 28))
print(startsOneEnds(n: 29))
print(startsOneEnds(n: 30))
print(startsOneEnds(n: 31))
print(startsOneEnds(n: 32))
print(startsOneEnds(n: 33))
print(startsOneEnds(n: 34))
print(startsOneEnds(n: 35))
print(startsOneEnds(n: 36))
print(startsOneEnds(n: 37))
print(startsOneEnds(n: 38))
print(startsOneEnds(n: 39))
print(startsOneEnds(n: 40))
print(startsOneEnds(n: 41))
print(startsOneEnds(n: 42))
print(startsOneEnds(n: 43))
print(startsOneEnds(n: 44))
print(startsOneEnds(n: 45))
print(startsOneEnds(n: 46))
print(startsOneEnds(n: 47))
print(startsOneEnds(n: 48))
print(startsOneEnds(n: 49))
print(startsOneEnds(n: 50))
print(startsOneEnds(n: 51))
print(startsOneEnds(n: 52))
print(startsOneEnds(n: 53))
print(startsOneEnds(n: 54))
print(startsOneEnds(n: 55))
print(startsOneEnds(n: 56))
print(startsOneEnds(n: 57))
print(startsOneEnds(n: 58))
print(startsOneEnds(n: 59))
print(startsOneEnds(n: 60))
print(startsOneEnds(n: 61))
print(startsOneEnds(n: 62))
print(startsOneEnds(n: 63))
print(startsOneEnds(n: 64))
print(startsOneEnds(n: 65))
print(startsOneEnds(n: 66))
print(startsOneEnds(n: 67))
print(startsOneEnds(n: 68))
print(startsOneEnds(n: 69))
print(startsOneEnds(n: 70))
print(startsOneEnds(n: 71))
print(startsOneEnds(n: 72))
print(startsOneEnds(n: 73))
print(startsOne
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
let count = pow(10, n - 1)
return Int(count)
}
func startsOneEndsOne(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsZero(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsTwo(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsThree(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsFour(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsFive(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsSix(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsSeven(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsEight(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
func startsOneEndsNine(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(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 {
let count = pow(10, n - 1)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1.
func startsOneEndsOne(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 0.
func startsOneEndsZero(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 2.
func startsOneEndsTwo(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 3.
func startsOneEndsThree(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 4.
func startsOneEndsFour(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 5.
func startsOneEndsFive(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 6.
func startsOneEndsSix(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 7.
func startsOneEndsSeven(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 8.
func startsOneEndsEight(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 9.
func startsOneEndsNine(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 0.
func startsOneEndsZero(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 1.
func startsOneEndsOne(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start with 1 and end with 2.
func startsOneEndsTwo(n: Int) -> Int {
let count = pow(10, n - 2)
return Int(count)
}
// Given a positive integer n, return
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
return Int(count) // no exact matches in call to initializer
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
return count * 10 + 9 * (count - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
return count * 10 + 9 * (count - 1)
}
print(startsOneEnds(n: 2))
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 10
}
let count = startsOneEnds(n: n - 1)
return count * 9
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 10
}
let count = startsOneEnds(n: n - 1)
return count * 9
}
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 10
}
let count = startsOneEnds(n: n - 1)
return count * 9
}
print(startsOneEnds(n: 2))
print(startsOneEnds(n: 3))
print(startsOneEnds(n: 4))
print(startsOneEnds(n: 5))
print(startsOneEnds(n: 6))
print(startsOneEnds(n: 7))
print(startsOneEnds(n: 8))
print(startsOneEnds(n: 9))
print(startsOneEnds(n: 10))
print(startsOneEnds(n: 11))
print(startsOneEnds(n: 12))
print(startsOneEnds(n: 13))
print(startsOneEnds(n: 14))
print(startsOneEnds(n: 15))
print(startsOneEnds(n: 16))
print(startsOneEnds(n: 17))
print(startsOneEnds(n: 18))
print(startsOneEnds(n: 19))
print(startsOneEnds(n: 20))
print(startsOneEnds(n: 21))
print(startsOneEnds(n: 22))
print(startsOneEnds(n: 23))
print(startsOneEnds(n: 24))
print(startsOneEnds(n: 25))
print(startsOneEnds(n: 26))
print(startsOneEnds(n: 27))
print(startsOneEnds(n: 28))
print(startsOneEnds(n: 29))
print(startsOneEnds(n: 30))
print(startsOneEnds(n: 31))
print(startsOneEnds(n: 32))
print(startsOneEnds(n: 33))
print(startsOneEnds(n: 34))
print(startsOneEnds(n: 35))
print(startsOneEnds(n: 36))
print(startsOneEnds(n: 37))
print(startsOneEnds(n: 38))
print(startsOneEnds(n: 39))
print(startsOneEnds(n: 40))
print(startsOneEnds(n: 41))
print(startsOneEnds(n: 42))
print(startsOneEnds(n: 43))
print(startsOneEnds(n: 44))
print(startsOneEnds(n: 45))
print(startsOneEnds(n: 46))
print(startsOneEnds(n: 47))
print(startsOneEnds(n: 48))
print(startsOneEnds(n: 49))
print(startsOneEnds(n: 50))
print(startsOneEnds(n: 51))
print(startsOneEnds(n: 52))
print(startsOneEnds(n: 53))
print(startsOneEnds(n: 54))
print(startsOneEnds(n: 55))
print(startsOneEnds(n: 56))
print(startsOneEnds(n: 57))
print(startsOneEnds(n: 58))
print(startsOneEnds(n: 59))
print(startsOneEnds(n: 60))
print(startsOneEnds(n: 61))
print(startsOneEnds(n: 62))
print(startsOneEnds(n: 63))
print(startsOneEnds(n: 64))
print(startsOneEnds(n: 65))
print(startsOneEnds(n: 66))
print(startsOneEnds(n: 67))
print(startsOneEnds(n: 68))
print(startsOneEnds(n: 69))
print(startsOneEnds(n: 70))
print(startsOneEnds(n: 71))
print(startsOneEnds(n: 72))
print(startsOneEnds(n
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
return 9 * count
}
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOne(n: n - 1)
return 9 * count
}
func startsOneEndsOneNoZero(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZero(n: n - 1)
return 8 * count
}
func startsOneEndsOneNoZeroNoLeadingZero(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZero(n: n - 1)
return 8 * count
}
func startsOneEndsOneNoZeroNoLeadingZeroNoTwo(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwo(n: n - 1)
return 7 * count
}
func startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThree(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThree(n: n - 1)
return 6 * count
}
func startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFour(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFour(n: n - 1)
return 5 * count
}
func startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFourNoFive(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFourNoFive(n: n - 1)
return 4 * count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
return 9 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1.
func startsOneEndsOne(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOne(n: n - 1)
return 9 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the middle.
func startsOneEndsOneNoZero(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZero(n: n - 1)
return 8 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the middle.
// The numbers cannot have leading zeros either.
func startsOneEndsOneNoZeroNoLeadingZero(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZero(n: n - 1)
return 8 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the middle.
// The numbers cannot have leading zeros either.
// The numbers cannot have 2 in the middle either.
func startsOneEndsOneNoZeroNoLeadingZeroNoTwo(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwo(n: n - 1)
return 7 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the middle.
// The numbers cannot have leading zeros either.
// The numbers cannot have 2 in the middle either.
// The numbers cannot have 3 in the middle either.
func startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThree(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThree(n: n - 1)
return 6 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the middle.
// The numbers cannot have leading zeros either.
// The numbers cannot have 2 in the middle either.
// The numbers cannot have 3 in the middle either.
// The numbers cannot have 4 in the middle either.
func startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFour(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFour(n: n - 1)
return 5 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the middle.
// The numbers cannot have leading zeros either.
// The numbers cannot have 2 in the middle either.
// The numbers cannot have 3 in the middle either.
// The numbers cannot have 4 in the middle either.
// The numbers cannot have 5 in the middle either.
func startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFourNoFive(n: Int) -> Int {
if n == 1 {
return 1
}
let count = startsOneEndsOneNoZeroNoLeadingZeroNoTwoNoThreeNoFourNoFive(n: n - 1)
return 4 * count
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start and end with 1 and do not have 0 in the
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
let count1 = count * 9
let count2 = (count - 1) * 8
return count1 + count2
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
let count = startsOneEnds(n: n - 1)
let count1 = count * 9
let count2 = (count - 1) * 8
return count1 + count2
}
print(startsOneEnds(n: 2))
print(startsOneEnds(n: 3))
print(startsOneEnds(n: 4))
print(startsOneEnds(n: 5))
print(startsOneEnds(n: 6))
print(startsOneEnds(n: 7))
print(startsOneEnds(n: 8))
print(startsOneEnds(n: 9))
print(startsOneEnds(n: 10))
print(startsOneEnds(n: 11))
print(startsOneEnds(n: 12))
print(startsOneEnds(n: 13))
print(startsOneEnds(n: 14))
print(startsOneEnds(n: 15))
print(startsOneEnds(n: 16))
print(startsOneEnds(n: 17))
print(startsOneEnds(n: 18))
print(startsOneEnds(n: 19))
print(startsOneEnds(n: 20))
print(startsOneEnds(n: 21))
print(startsOneEnds(n: 22))
print(startsOneEnds(n: 23))
print(startsOneEnds(n: 24))
print(startsOneEnds(n: 25))
print(startsOneEnds(n: 26))
print(startsOneEnds(n: 27))
print(startsOneEnds(n: 28))
print(startsOneEnds(n: 29))
print(startsOneEnds(n: 30))
print(startsOneEnds(n: 31))
print(startsOneEnds(n: 32))
print(startsOneEnds(n: 33))
print(startsOneEnds(n: 34))
print(startsOneEnds(n: 35))
print(startsOneEnds(n: 36))
print(startsOneEnds(n: 37))
print(startsOneEnds(n: 38))
print(startsOneEnds(n: 39))
print(startsOneEnds(n: 40))
print(startsOneEnds(n: 41))
print(startsOneEnds(n: 42))
print(startsOneEnds(n: 43))
print(startsOneEnds(n: 44))
print(startsOneEnds(n: 45))
print(startsOneEnds(n: 46))
print(startsOneEnds(n: 47))
print(startsOneEnds(n: 48))
print(startsOneEnds(n: 49))
print(startsOneEnds(n: 50))
print(startsOneEnds(n: 51))
print(startsOneEnds(n: 52))
print(startsOneEnds(n: 53))
print(startsOneEnds(n: 54))
print(startsOneEnds(n: 55))
print(startsOneEnds(n: 56))
print(startsOneEnds(n: 57))
print(startsOneEnds(n: 58))
print(startsOneEnds(n: 59))
print(startsOneEnds(n: 60))
print(startsOneEnds(n: 61))
print(startsOneEnds(n: 62))
print(startsOneEnds(n: 63))
print(startsOneEnds(n: 64))
print(startsOneEnds(n: 65))
print(startsOneEnds(n: 66))
print(startsOneEnds(n: 67))
print(startsOneEnds(n: 68))
print(startsOneEnds(n: 69))
print(startsOneEnds(n: 70))
print(startsOneEnds(n: 71))
print(startsOneEnds(n: 72))
print(startsOneEnds(n: 73))
print(startsOneEnds(n: 74))
print(startsOneEnds(n: 75
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, 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 {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, radix: 2)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, 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 {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, radix: 2)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, 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 {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, radix: 2)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int(String($1))! }
return String(sum, 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 {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int(String($1))! }
return String(sum, radix: 2)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, 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 {
let binary = String(N, radix: 2)
let sum = binary.reduce(0) { $0 + Int($1.description)! }
return String(sum, radix: 2)
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(N, radix: 2)
var sum = 0
for char in binary {
sum += Int(String(char))!
}
return String(sum)
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
print(add(lst: [4, 2, 6, 7]))
```
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 != 0 && value % 2 == 0 {
sum += value
}
}
return sum
}
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
print(add(lst: [4, 2, 6, 7]))
```
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 != 0 && lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
print(antiShuffle(s: "Hello World!!!"))
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```
func antiShuffle(s: String) -> String {
var words = s.components(separatedBy: " ")
for (index, word) in words.enumerated() {
var chars = Array(word)
chars.sort()
words[index] = String(chars)
}
return words.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.components(separatedBy: " ")
for (index, word) in words.enumerated() {
var chars = Array(word)
chars.sort()
words[index] = String(chars)
}
return words.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords = [String]()
for word in words {
let charArray = Array(word)
let sortedArray = charArray.sorted {
$0 < $1
}
let newWord = String(sortedArray)
newWords.append(newWord)
}
return newWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords = [String]()
for word in words {
let charArray = Array(word)
let sortedArray = charArray.sorted {
$0 < $1
}
let newWord = String(sortedArray)
newWords.append(newWord)
}
return newWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords = [String]()
for word in words {
let sortedWord = String(word.sorted())
newWords.append(sortedWord)
}
return newWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords = [String]()
for word in words {
let sortedWord = String(word.sorted())
newWords.append(sortedWord)
}
return newWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
var words = s.components(separatedBy: " ")
for i in 0..<words.count {
var chars = Array(words[i])
chars.sort()
words[i] = String(chars)
}
return words.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.components(separatedBy: " ")
for i in 0..<words.count {
var chars = Array(words[i])
chars.sort()
words[i] = String(chars)
}
return words.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
let sortedWord = String(word.sorted())
result += sortedWord + " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords = [String]()
for word in words {
var newWord = ""
let charArray = Array(word)
let sortedArray = charArray.sorted { $0 < $1 }
for char in sortedArray {
newWord += String(char)
}
newWords.append(newWord)
}
return newWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var newWords = [String]()
for word in words {
var newWord = ""
let charArray = Array(word)
let sortedArray = charArray.sorted { $0 < $1 }
for char in sortedArray {
newWord += String(char)
}
newWords.append(newWord)
}
return newWords.joined(separator: " ")
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (colIndex, value) in row.enumerated() {
if value == x {
result.append((index, colIndex))
}
}
}
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 (colIndex, value) in row.enumerated() {
if value == x {
result.append((index, colIndex))
}
}
}
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 (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
result.sort { $0.0 < $1.0 || ($0.0 == $1.0 && $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 || ($0.0 == $1.0 && $0.1 > $1.1) }
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
if let index = row.firstIndex(of: x) {
result.append((index, index))
}
}
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() {
if let index = row.firstIndex(of: x) {
result.append((index, index))
}
}
return result
}
```
for (index, row) in lst.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort { $0.0 < $1.0 || ($0.0 == $1.0 && $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, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.1) }
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
if let index = row.firstIndex(of: x) {
result.append((index, index))
}
}
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() {
if let index = row.firstIndex(of: x) {
result.append((index, index))
}
}
return result
}
```
for (index, row) in lst.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
return result.sorted {
if $0.0 == $1.0 {
return $0.1 > $1.1
}
return $0.0 < $1.0
}
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result: [(Int, Int)] = []
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated() {
if value == x {
result.append((index, column))
}
}
}
return result.sorted {
if $0.0 == $1.0 {
return $0.1 > $1.1
}
return $0.0 < $1.0
}
}
```
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 (i, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort { $0.0 < $1.0 || ($0.0 == $1.0 && $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, row) in lst.enumerated() {
for (j, value) in row.enumerated() {
if value == x {
result.append((i, j))
}
}
}
result.sort { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.1) }
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
if let index = row.firstIndex(of: x) {
result.append((i, index))
}
}
return result.sorted { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.0) }
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
if let index = row.firstIndex(of: x) {
result.append((i, index))
}
}
return result.sorted { $0.0 < $1.0 || ($0.0 == $1.0 && $0.1 > $1.0) }
}
```
// 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 || ($0.0 == $1.0 && $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 || ($0.0 == $1.0 && $0.1 > $1.1) }
return result
}
```
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
array.sort { (a, b) -> Bool in
if (sum % 2 == 0) {
return a > b
} else {
return a < b
}
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
array.sort { (a, b) -> Bool in
if (sum % 2 == 0) {
return a > b
} else {
return a < b
}
}
return array
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var arr = array
let sum = arr.reduce(0, +)
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort()
}
return arr
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var arr = array
let sum = arr.reduce(0, +)
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort()
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var arr = array
var sum = 0
for i in 0..<arr.count {
sum += arr[i]
}
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort(by: <)
}
return arr
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var arr = array
var sum = 0
for i in 0..<arr.count {
sum += arr[i]
}
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort(by: <)
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var arr = array
let sum = arr.reduce(0, +)
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort(by: <)
}
return arr
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var arr = array
let sum = arr.reduce(0, +)
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort(by: <)
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
if sum % 2 == 0 {
array.sort(by: >)
} else {
array.sort()
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
if sum % 2 == 0 {
array.sort(by: >)
} else {
array.sort()
}
return array
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
if sum % 2 == 0 {
array.sort(by: >)
} else {
array.sort()
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
if sum % 2 == 0 {
array.sort(by: >)
} else {
array.sort()
}
return array
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.reduce(0, +)
let isOdd = sum % 2 == 1
let sorted = array.sorted(by: { isOdd ? $0 < $1 : $0 > $1 })
return sorted
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let sum = array.reduce(0, +)
let isOdd = sum % 2 == 1
let sorted = array.sorted(by: { isOdd ? $0 < $1 : $0 > $1 })
return sorted
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else {
return array
}
let sortedArray = array.sorted()
let sum = sortedArray.first! + sortedArray.last!
if sum % 2 == 0 {
return sortedArray.reversed()
} else {
return sortedArray
}
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 1 else {
return array
}
let sortedArray = array.sorted()
let sum = sortedArray.first! + sortedArray.last!
if sum % 2 == 0 {
return sortedArray.reversed()
} else {
return sortedArray
}
}
```
func sortArray(array: [Int]) -> [Int] {
var arr = array
let sum = arr.reduce(0, +)
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort()
}
return arr
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var arr = array
let sum = arr.reduce(0, +)
if sum % 2 == 0 {
arr.sort(by: >)
} else {
arr.sort()
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
array.sort(by: {
if (sum % 2 == 0) {
return $0 > $1
} else {
return $0 < $1
}
})
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var array = array
let sum = array.reduce(0, +)
array.sort(by: {
if (sum % 2 == 0) {
return $0 > $1
} else {
return $0 < $1
}
})
return array
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
let charIndex = alphabet.index(of: char)
let newIndex = alphabet.index(charIndex!, offsetBy: 4)
let newChar = alphabet[newIndex!]
encryptedString.append(newChar)
}
return encryptedString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
let charIndex = alphabet.index(of: char)
let newIndex = alphabet.index(charIndex!, offsetBy: 4)
let newChar = alphabet[newIndex!]
encryptedString.append(newChar)
}
return encryptedString
}
```
let charIndex = alphabet.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
let newChar = alphabet[newIndex!] // cannot force unwrap value of non-optional type 'String.Index'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
let charIndex = alphabet.index(of: char)!
let newIndex = charIndex + (2 * 2)
let newChar = alphabet[alphabet.index(alphabet.startIndex, offsetBy: newIndex)]
encryptedString += String(newChar)
}
return encryptedString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
let charIndex = alphabet.index(of: char)!
let newIndex = charIndex + (2 * 2)
let newChar = alphabet[alphabet.index(alphabet.startIndex, offsetBy: newIndex)]
encryptedString += String(newChar)
}
return encryptedString
}
```
let charIndex = alphabet.index(of: char)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
let newIndex = charIndex + (2 * 2) // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let lowerCaseString = s.lowercased()
var encryptedString = ""
for char in lowerCaseString {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
encryptedString += String(newChar)
}
return encryptedString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let lowerCaseString = s.lowercased()
var encryptedString = ""
for char in lowerCaseString {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
encryptedString += String(newChar)
}
return encryptedString
}
```
for char in lowerCaseString { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
let charIndex = alphabet.index(of: char)
let newIndex = alphabet.index(charIndex!, offsetBy: 4)
let newChar = alphabet[newIndex!]
encryptedString += String(newChar)
}
return encryptedString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encryptedString = ""
for char in s {
let charIndex = alphabet.index(of: char)
let newIndex = alphabet.index(charIndex!, offsetBy: 4)
let newChar = alphabet[newIndex!]
encryptedString += String(newChar)
}
return encryptedString
}
```
let charIndex = alphabet.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
let newChar = alphabet[newIndex!] // cannot force unwrap value of non-optional type 'String.Index'
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
let charValue = Int(char.asciiValue!)
if charValue >= 97 && charValue <= 122 {
let newCharValue = charValue + 4
if newCharValue > 122 {
let newCharValue = newCharValue - 26
let newChar = String(UnicodeScalar(newCharValue)!)
encrypted += newChar
} else {
let newChar = String(UnicodeScalar(newCharValue)!)
encrypted += newChar
}
} else {
let newChar = String(UnicodeScalar(charValue)!)
encrypted += newChar
}
}
return encrypted
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
let charValue = Int(char.asciiValue!)
if charValue >= 97 && charValue <= 122 {
let newCharValue = charValue + 4
if newCharValue > 122 {
let newCharValue = newCharValue - 26
let newChar = String(UnicodeScalar(newCharValue)!)
encrypted += newChar
} else {
let newChar = String(UnicodeScalar(newCharValue)!)
encrypted += newChar
}
} else {
let newChar = String(UnicodeScalar(charValue)!)
encrypted += newChar
}
}
return encrypted
}
```
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
encrypted += String(newChar)
}
return encrypted
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
encrypted += String(newChar)
}
return encrypted
}
```
for char in s { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func encrypt(s: String) -> String {
var encryptedString = ""
let alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2)
let newChar = alphabet.replacingCharacters(in: index..., with: "\(char)")
encryptedString += newChar
}
return encryptedString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var encryptedString = ""
let alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2)
let newChar = alphabet.replacingCharacters(in: index..., with: "\(char)")
encryptedString += newChar
}
return encryptedString
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
if char == " " {
encrypted += " "
} else if char == "z" {
encrypted += "b"
} else if char == "y" {
encrypted += "a"
} else if char == "x" {
encrypted += "z"
} else if char == "w" {
encrypted += "y"
} else if char == "v" {
encrypted += "x"
} else if char == "u" {
encrypted += "w"
} else if char == "t" {
encrypted += "v"
} else if char == "s" {
encrypted += "u"
} else if char == "r" {
encrypted += "t"
} else if char == "q" {
encrypted += "s"
} else if char == "p" {
encrypted += "r"
} else if char == "o" {
encrypted += "q"
} else if char == "n" {
encrypted += "p"
} else if char == "m" {
encrypted += "o"
} else if char == "l" {
encrypted += "n"
} else if char == "k" {
encrypted += "m"
} else if char == "j" {
encrypted += "l"
} else if char == "i" {
encrypted += "k"
} else if char == "h" {
encrypted += "j"
} else if char == "g" {
encrypted += "i"
} else if char == "f" {
encrypted += "h"
} else if char == "e" {
encrypted += "g"
} else if char == "d" {
encrypted += "f"
} else if char == "c" {
encrypted += "e"
} else if char == "b" {
encrypted += "d"
} else if char == "a" {
encrypted += "c"
}
}
return encrypted
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var encrypted = ""
for char in s {
if char == " " {
encrypted += " "
} else if char == "z" {
encrypted += "b"
} else if char == "y" {
encrypted += "a"
} else if char == "x" {
encrypted += "z"
} else if char == "w" {
encrypted += "y"
} else if char == "v" {
encrypted += "x"
} else if char == "u" {
encrypted += "w"
} else if char == "t" {
encrypted += "v"
} else if char == "s" {
encrypted += "u"
} else if char == "r" {
encrypted += "t"
} else if char == "q" {
encrypted += "s"
} else if char == "p" {
encrypted += "r"
} else if char == "o" {
encrypted += "q"
} else if char == "n" {
encrypted += "p"
} else if char == "m" {
encrypted += "o"
} else if char == "l" {
encrypted += "n"
} else if char == "k" {
encrypted += "m"
} else if char == "j" {
encrypted += "l"
} else if char == "i" {
encrypted += "k"
} else if char == "h" {
encrypted += "j"
} else if char == "g" {
encrypted += "i"
} else if char == "f" {
encrypted += "h"
} else if char == "e" {
encrypted += "g"
} else if char == "d" {
encrypted += "f"
} else if char == "c" {
encrypted += "e"
} else if char == "b" {
encrypted += "d"
} else if char == "a" {
encrypted += "c"
}
}
return encrypted
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
var result = ""
let alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
result += String(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 = ""
let alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
result += String(newChar)
}
return result
}
```
for char in s { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func encrypt(s: String) -> String {
var encryptedString = ""
let alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
encryptedString += String(newChar)
}
return encryptedString
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var encryptedString = ""
let alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in s {
let index = alphabet.index(alphabet.startIndex, offsetBy: 2 * 2)
let newChar = alphabet[index]
encryptedString += String(newChar)
}
return encryptedString
}
```
for char in s { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard let smallest = lst.min() else { return nil }
let filtered = lst.filter { $0 > smallest }
guard let secondSmallest = filtered.min() else { return nil }
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard let smallest = lst.min() else { return nil }
let filtered = lst.filter { $0 > smallest }
guard let secondSmallest = filtered.min() else { return nil }
return secondSmallest
}
```
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let smallest = sorted.first!
let secondSmallest = sorted[1]
return lst.contains(secondSmallest) ? secondSmallest : 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? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let smallest = sorted.first!
let secondSmallest = sorted[1]
return lst.contains(secondSmallest) ? secondSmallest : nil
}
```
let smallest = sorted.first! // initialization of immutable value 'smallest' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
let secondSmallest = sorted[1]
return lst.contains(secondSmallest) ? secondSmallest : 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? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
let secondSmallest = sorted[1]
return lst.contains(secondSmallest) ? secondSmallest : nil
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
guard let secondSmallest = sorted.first(where: { $0 != sorted[0] }) else { return nil }
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
guard let secondSmallest = sorted.first(where: { $0 != sorted[0] }) else { return nil }
return secondSmallest
}
```
func nextSmallest(lst: [Int]) -> Int? {
guard let smallest = lst.min() else { return nil }
guard let secondSmallest = lst.filter({ $0 > smallest }).min() else { return nil }
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard let smallest = lst.min() else { return nil }
guard let secondSmallest = lst.filter({ $0 > smallest }).min() else { return nil }
return secondSmallest
}
```
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let min = sorted.first!
let secondMin = sorted[1]
return lst.contains(secondMin) ? secondMin : 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? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let min = sorted.first!
let secondMin = sorted[1]
return lst.contains(secondMin) ? secondMin : nil
}
```
let min = sorted.first! // initialization of immutable value 'min' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let secondSmallest = sorted[1]
guard lst.contains(secondSmallest) else { return nil }
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let secondSmallest = sorted[1]
guard lst.contains(secondSmallest) else { return nil }
return secondSmallest
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
guard let secondSmallest = sorted.first(where: { $0 != sorted.first }) else { return nil }
return secondSmallest
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
guard let secondSmallest = sorted.first(where: { $0 != sorted.first }) else { return nil }
return secondSmallest
}
```
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let first = sorted.first!
let second = sorted.dropFirst().first!
return first == second ? nil : second
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
guard lst.count > 2 else { return lst.min() }
let sorted = lst.sorted()
let first = sorted.first!
let second = sorted.dropFirst().first!
return first == second ? nil : second
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
let smallest = sorted.first!
let secondSmallest = sorted.dropFirst().first!
return lst.contains(secondSmallest) ? secondSmallest : 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? {
guard lst.count > 1 else { return nil }
let sorted = lst.sorted()
let smallest = sorted.first!
let secondSmallest = sorted.dropFirst().first!
return lst.contains(secondSmallest) ? secondSmallest : nil
}
```
let smallest = sorted.first! // initialization of immutable value 'smallest' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: [" ", ".", "?", "!"])
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: [" ", ".", "?", "!"])
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for (index, word) in words.enumerated() {
if word == "I" {
if index != 0 && words[index - 1] != "." && words[index - 1] != "?" && words[index - 1] != "!" {
count += 1
}
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for (index, word) in words.enumerated() {
if word == "I" {
if index != 0 && words[index - 1] != "." && words[index - 1] != "?" && words[index - 1] != "!" {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var count = 0
let words = S.components(separatedBy: " ")
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
let words = S.components(separatedBy: " ")
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: [" ", ".", "?", "!"])
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: [" ", ".", "?", "!"])
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let sentences = S.components(separatedBy: ["?", "!", "."])
var boredoms = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
boredoms += 1
}
}
return boredoms
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let sentences = S.components(separatedBy: ["?", "!", "."])
var boredoms = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
boredoms += 1
}
}
return boredoms
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for i in 0..<words.count {
if words[i] == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for i in 0..<words.count {
if words[i] == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for i in 0..<words.count {
if words[i] == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var count = 0
for i in 0..<words.count {
if words[i] == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredoms = 0
for (index, word) in words.enumerated() {
if word == "I" {
if index < words.count - 1 {
if words[index + 1] == "am" {
boredoms += 1
}
}
}
}
return boredoms
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: " ")
var boredoms = 0
for (index, word) in words.enumerated() {
if word == "I" {
if index < words.count - 1 {
if words[index + 1] == "am" {
boredoms += 1
}
}
}
}
return boredoms
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
let sum2 = x + z
let sum3 = y + z
if x == sum || y == sum2 || z == sum3 {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
let sum2 = x + z
let sum3 = y + z
if x == sum || y == sum2 || z == sum3 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if sum == z {
return true
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if sum == z {
return true
}
return false
}
```
// 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 {
if x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || y == x + z || z == x + y {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if sum == z {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if sum == z {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if x == sum || y == sum || z == sum {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
if x == sum || y == sum || z == sum {
return true
} else {
return false
}
}
```
// 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)
}
```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 {
let sum = x + y
let sum2 = x + z
let sum3 = y + z
if x == sum || y == sum2 || z == sum3 {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y
let sum2 = x + z
let sum3 = y + z
if x == sum || y == sum2 || z == sum3 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char.isLetter {
let char = char.uppercased()
let charValue = char.unicodeScalars.first!.value
if charValue >= 65 && charValue <= 90 {
let newCharValue = charValue + 2
if newCharValue > 90 {
newMessage += String(UnicodeScalar(newCharValue - 26)!)
} else {
newMessage += String(UnicodeScalar(newCharValue)!)
}
} else if charValue >= 97 && charValue <= 122 {
let newCharValue = charValue + 2
if newCharValue > 122 {
newMessage += String(UnicodeScalar(newCharValue - 26)!)
} else {
newMessage += String(UnicodeScalar(newCharValue)!)
}
}
} else if char.isVowel {
let char = char.lowercased()
let charValue = char.unicodeScalars.first!.value
if charValue == 97 {
newMessage += "b"
} else if charValue == 101 {
newMessage += "d"
} else if charValue == 105 {
newMessage += "f"
} else if charValue == 111 {
newMessage += "h"
} else if charValue == 117 {
newMessage += "j"
}
} else {
newMessage += String(char)
}
}
return newMessage
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char.isLetter {
let char = char.uppercased()
let charValue = char.unicodeScalars.first!.value
if charValue >= 65 && charValue <= 90 {
let newCharValue = charValue + 2
if newCharValue > 90 {
newMessage += String(UnicodeScalar(newCharValue - 26)!)
} else {
newMessage += String(UnicodeScalar(newCharValue)!)
}
} else if charValue >= 97 && charValue <= 122 {
let newCharValue = charValue + 2
if newCharValue > 122 {
newMessage += String(UnicodeScalar(newCharValue - 26)!)
} else {
newMessage += String(UnicodeScalar(newCharValue)!)
}
}
} else if char.isVowel {
let char = char.lowercased()
let charValue = char.unicodeScalars.first!.value
if charValue == 97 {
newMessage += "b"
} else if charValue == 101 {
newMessage += "d"
} else if charValue == 105 {
newMessage += "f"
} else if charValue == 111 {
newMessage += "h"
} else if charValue == 117 {
newMessage += "j"
}
} else {
newMessage += String(char)
}
}
return newMessage
}
```
} else if char.isVowel { // value of type 'Character' has no member 'isVowel'
func encode(message: String) -> String {
let vowels = "aeiouAEIOU"
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var encodedMessage = ""
for char in message {
if vowels.contains(char) {
let index = alphabet.firstIndex(of: char)!
let newIndex = index + 2
let newChar = alphabet[newIndex]
encodedMessage += String(newChar)
} else {
let newChar = char.uppercased()
encodedMessage += String(newChar)
}
}
return encodedMessage
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels = "aeiouAEIOU"
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var encodedMessage = ""
for char in message {
if vowels.contains(char) {
let index = alphabet.firstIndex(of: char)!
let newIndex = index + 2
let newChar = alphabet[newIndex]
encodedMessage += String(newChar)
} else {
let newChar = char.uppercased()
encodedMessage += String(newChar)
}
}
return encodedMessage
}
```
let newIndex = index + 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.isLetter {
let char = char.uppercased()
let charValue = char.unicodeScalars.first!.value
if charValue >= 65 && charValue <= 90 {
let newCharValue = charValue + 2
let newChar = UnicodeScalar(newCharValue)!
newMessage += String(newChar)
} else if charValue >= 97 && charValue <= 122 {
let newCharValue = charValue + 2
let newChar = UnicodeScalar(newCharValue)!
newMessage += String(newChar)
}
} else {
newMessage += String(char)
}
}
return newMessage
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char.isLetter {
let char = char.uppercased()
let charValue = char.unicodeScalars.first!.value
if charValue >= 65 && charValue <= 90 {
let newCharValue = charValue + 2
let newChar = UnicodeScalar(newCharValue)!
newMessage += String(newChar)
} else if charValue >= 97 && charValue <= 122 {
let newCharValue = charValue + 2
let newChar = UnicodeScalar(newCharValue)!
newMessage += String(newChar)
}
} else {
newMessage += String(char)
}
}
return newMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isUppercase {
newString += String(char).lowercased()
} else if char.isLowercase {
newString += String(char).uppercased()
}
}
var newString2 = ""
for char in newString {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
if char == "a" {
newString2 += "c"
} else if char == "e" {
newString2 += "g"
} else if char == "i" {
newString2 += "k"
} else if char == "o" {
newString2 += "q"
} else if char == "u" {
newString2 += "y"
}
} else {
newString2 += String(char)
}
}
return newString2
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isUppercase {
newString += String(char).lowercased()
} else if char.isLowercase {
newString += String(char).uppercased()
}
}
var newString2 = ""
for char in newString {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
if char == "a" {
newString2 += "c"
} else if char == "e" {
newString2 += "g"
} else if char == "i" {
newString2 += "k"
} else if char == "o" {
newString2 += "q"
} else if char == "u" {
newString2 += "y"
}
} else {
newString2 += String(char)
}
}
return newString2
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var newMessage = ""
for char in message {
if char.isLetter {
if char.isUppercase {
newMessage.append(char.lowercased())
} else {
newMessage.append(char.uppercased())
}
} else {
newMessage.append(char)
}
}
let vowels = ["a", "e", "i", "o", "u"]
var newMessage2 = ""
for char in newMessage {
if vowels.contains(String(char)) {
let charIndex = vowels.firstIndex(of: String(char))!
let newChar = vowels[(charIndex + 2) % vowels.count]
newMessage2.append(newChar)
} else {
newMessage2.append(char)
}
}
return newMessage2
}
```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.isLetter {
if char.isUppercase {
newMessage.append(char.lowercased())
} else {
newMessage.append(char.uppercased())
}
} else {
newMessage.append(char)
}
}
let vowels = ["a", "e", "i", "o", "u"]
var newMessage2 = ""
for char in newMessage {
if vowels.contains(String(char)) {
let charIndex = vowels.firstIndex(of: String(char))!
let newChar = vowels[(charIndex + 2) % vowels.count]
newMessage2.append(newChar)
} else {
newMessage2.append(char)
}
}
return newMessage2
}
```
// XCTAssertTrue failed
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isLetter {
let char = String(char).lowercased()
let char = char.replacingOccurrences(of: "a", with: "c")
let char = char.replacingOccurrences(of: "e", with: "g")
let char = char.replacingOccurrences(of: "i", with: "k")
let char = char.replacingOccurrences(of: "o", with: "q")
let char = char.replacingOccurrences(of: "u", with: "y")
let char = char.replacingOccurrences(of: "y", with: "b")
let char = char.replacingOccurrences(of: "c", with: "e")
let char = char.replacingOccurrences(of: "g", with: "i")
let char = char.replacingOccurrences(of: "k", with: "o")
let char = char.replacingOccurrences(of: "q", with: "u")
let char = char.replacingOccurrences(of: "y", with: "a")
let char = char.replacingOccurrences(of: "b", with: "e")
let char = char.replacingOccurrences(of: "c", with: "i")
let char = char.replacingOccurrences(of: "e", with: "o")
let char = char.replacingOccurrences(of: "i", with: "u")
let char = char.replacingOccurrences(of: "o", with: "y")
let char = char.replacingOccurrences(of: "u", with: "a")
let char = char.replacingOccurrences(of: "y", with: "e")
let char = char.replacingOccurrences(of: "a", with: "i")
let char = char.replacingOccurrences(of: "e", with: "o")
let char = char.replacingOccurrences(of: "i", with: "u")
let char = char.replacingOccurrences(of: "o", with: "y")
let char = char.replacingOccurrences(of: "u", with: "a")
let char = char.replacingOccurrences(of: "y", with: "e")
let char = char.replacingOccurrences(of: "a", with: "i")
let char = char.replacingOccurrences(of: "e", with: "o")
let char = char.replacingOccurrences(of: "i", with: "u")
let char = char.replacingOccurrences(of: "o", with: "y")
let char = char.replacingOccurrences(of: "u", with: "a")
let char = char.replacingOccurrences(of: "y", with: "e")
let char = char.replacingOccurrences(of: "a", with: "i")
let char = char.replacingOccurrences(of: "e", with: "o")
let char = char.replacingOccurrences(of: "i", with: "u")
let char = char.replacingOccurrences(of: "o", with: "y")
let char = char.replacingOccurrences(of: "u", with: "a")
let char = char.replacingOccurrences(of: "y", with: "e")
let char = char.replacingOccurrences(of: "a", with: "i")
let char = char.replacingOccurrences(of: "e", with: "o")
let char = char.replacingOccurrences(of: "i", with: "u")
let char = char.replacingOccurrences(of: "o", with: "y")
let char = char.replacingOccurrences(of: "u", with: "a")
let char = char.replacingOccurrences(of: "y", with: "e")
let char = char.replacingOccurrences(of: "a", with: "i")
let char = char.replacingOccurrences(of: "e", with: "o")
let char = char.replacingOccurrences(of: "i", with: "u")
let char = char.replacingOccurrences(of: "o", with: "y")
let char = char.replacingOccurrences(of: "u", with: "a")
let char = char.replacingOccurrences(of: "y", with: "e")
let char = char.replacingOccurrences(of: "a", with: "i")
let char = char.replacingOccurrences(
XCTAssertTrue(encode(message: "TEST") == "tgst") // cannot find 'encode' in scope
XCTAssertTrue(encode(message: "Mudasir") == "mWDCSKR") // cannot find 'encode' in scope
XCTAssertTrue(encode(message: "YES") == "ygs") // cannot find 'encode' in scope
XCTAssertTrue(encode(message: "This is a message") == "tHKS KS C MGSSCGG") // cannot find 'encode' in scope
XCTAssertTrue(encode(message: "I DoNt KnOw WhAt tO WrItE") == "k dQnT kNqW wHcT Tq wRkTg") // cannot find 'encode' in scope
func encode(message: String) -> String {
var newMessage = ""
for letter in message {
if letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u" {
newMessage += String(letter).uppercased()
} else {
newMessage += String(letter).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 letter in message {
if letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u" {
newMessage += String(letter).uppercased()
} else {
newMessage += String(letter).lowercased()
}
}
return newMessage
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var newString = ""
for char in message {
if char == char.lowercased() {
newString += char.uppercased()
} else {
newString += char.lowercased()
}
}
var newString2 = ""
for char in newString {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
switch char {
case "a":
newString2 += "c"
case "e":
newString2 += "g"
case "i":
newString2 += "k"
case "o":
newString2 += "q"
case "u":
newString2 += "y"
default:
break
}
} else {
newString2 += String(char)
}
}
return newString2
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newString = ""
for char in message {
if char == char.lowercased() {
newString += char.uppercased()
} else {
newString += char.lowercased()
}
}
var newString2 = ""
for char in newString {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
switch char {
case "a":
newString2 += "c"
case "e":
newString2 += "g"
case "i":
newString2 += "k"
case "o":
newString2 += "q"
case "u":
newString2 += "y"
default:
break
}
} else {
newString2 += String(char)
}
}
return newString2
}
```
if char == char.lowercased() { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isLetter {
let charString = String(char)
let charStringLower = charString.lowercased()
let charStringUpper = charString.uppercased()
let charStringLowerIndex = charStringLower.index(charStringLower.startIndex, offsetBy: 2)
let charStringUpperIndex = charStringUpper.index(charStringUpper.startIndex, offsetBy: 2)
let charStringLower2 = String(charStringLower[charStringLowerIndex])
let charStringUpper2 = String(charStringUpper[charStringUpperIndex])
if charStringLower2 == "a" || charStringLower2 == "e" || charStringLower2 == "i" || charStringLower2 == "o" || charStringLower2 == "u" {
newString += charStringUpper2
} else {
newString += charStringLower2
}
} else {
newString += String(char)
}
}
return newString
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isLetter {
let charString = String(char)
let charStringLower = charString.lowercased()
let charStringUpper = charString.uppercased()
let charStringLowerIndex = charStringLower.index(charStringLower.startIndex, offsetBy: 2)
let charStringUpperIndex = charStringUpper.index(charStringUpper.startIndex, offsetBy: 2)
let charStringLower2 = String(charStringLower[charStringLowerIndex])
let charStringUpper2 = String(charStringUpper[charStringUpperIndex])
if charStringLower2 == "a" || charStringLower2 == "e" || charStringLower2 == "i" || charStringLower2 == "o" || charStringLower2 == "u" {
newString += charStringUpper2
} else {
newString += charStringLower2
}
} else {
newString += String(char)
}
}
return newString
}
```
// Fatal error: String index is out of bounds
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isUppercase {
newString.append(char.lowercased())
} else if char.isLowercase {
newString.append(char.uppercased())
}
}
var newString2 = ""
for char in newString {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
if char == "a" {
newString2.append("c")
} else if char == "e" {
newString2.append("g")
} else if char == "i" {
newString2.append("k")
} else if char == "o" {
newString2.append("q")
} else if char == "u" {
newString2.append("y")
}
} else {
newString2.append(char)
}
}
return newString2
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var newString = ""
for char in message {
if char.isUppercase {
newString.append(char.lowercased())
} else if char.isLowercase {
newString.append(char.uppercased())
}
}
var newString2 = ""
for char in newString {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
if char == "a" {
newString2.append("c")
} else if char == "e" {
newString2.append("g")
} else if char == "i" {
newString2.append("k")
} else if char == "o" {
newString2.append("q")
} else if char == "u" {
newString2.append("y")
}
} else {
newString2.append(char)
}
}
return newString2
}
print(encode(message: "test"))
print(encode(message: "This is a message"))
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var sum = 0
while max > 0 {
sum += max % 10
max /= 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 max = 0
for i in lst {
if i > max {
max = i
}
}
var sum = 0
while max > 0 {
sum += max % 10
max /= 10
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for num in lst {
if isPrime(num: num) {
largestPrime = max(largestPrime, num)
}
}
return sumOfDigits(num: largestPrime)
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for num in lst {
if isPrime(num: num) {
largestPrime = max(largestPrime, num)
}
}
return sumOfDigits(num: largestPrime)
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
```
func skjkasdkd(lst: [Int]) -> Int {
var prime = 0
var sum = 0
for i in lst {
if i > prime {
prime = i
}
}
var number = prime
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var prime = 0
var sum = 0
for i in lst {
if i > prime {
prime = i
}
}
var number = prime
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for num in lst {
if isPrime(num: num) {
largestPrime = max(largestPrime, num)
}
}
return sumOfDigits(num: largestPrime)
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for num in lst {
if isPrime(num: num) {
largestPrime = max(largestPrime, num)
}
}
return sumOfDigits(num: largestPrime)
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
```
func skjkasdkd(lst: [Int]) -> Int {
let prime = lst.filter { isPrime($0) }.max()!
let sum = String(prime).compactMap { Int(String($0)) }.reduce(0, +)
return sum
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// 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 {
let prime = lst.filter { isPrime($0) }.max()!
let sum = String(prime).compactMap { Int(String($0)) }.reduce(0, +)
return sum
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
func skjkasdkd(lst: [Int]) -> Int {
var prime = 0
for i in lst {
if i > prime {
prime = i
}
}
var sum = 0
for i in String(prime) {
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 prime = 0
for i in lst {
if i > prime {
prime = i
}
}
var sum = 0
for i in String(prime) {
sum += Int(String(i))!
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var maxPrime = 0
var maxPrimeIndex = 0
for (index, value) in lst.enumerated() {
if value > maxPrime {
maxPrime = value
maxPrimeIndex = index
}
}
var sum = 0
var num = maxPrime
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 maxPrimeIndex = 0
for (index, value) in lst.enumerated() {
if value > maxPrime {
maxPrime = value
maxPrimeIndex = index
}
}
var sum = 0
var num = maxPrime
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```
var maxPrimeIndex = 0 // variable 'maxPrimeIndex' was written to, but never read
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for i in lst {
if isPrime(num: i) && i > largestPrime {
largestPrime = i
}
}
return sumOfDigits(num: largestPrime)
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var num = num
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var largestPrime = 0
for i in lst {
if isPrime(num: i) && i > largestPrime {
largestPrime = i
}
}
return sumOfDigits(num: largestPrime)
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func sumOfDigits(num: Int) -> Int {
var sum = 0
var num = num
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
```
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
for i in lst {
if i > max {
max = i
}
}
var sum = 0
for i in String(max) {
sum += Int(String(i))!
}
return sum
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [2]
var i = 3
while i < n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
i += 1
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [2]
var i = 3
while i < n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
i += 1
}
return primes
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var primes = [Int]()
for i in 2..<n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(i)
}
}
return primes
}
```
// Fatal error: Range requires lowerBound <= upperBound
func multiply(a: Int, b: Int) -> Int {
let first = a % 10
let second = b % 10
return first * second
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let first = a % 10
let second = b % 10
return first * second
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let first = a % 10
let second = b % 10
return first * second
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let first = a % 10
let second = b % 10
return first * second
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a1 = a % 10
let b1 = b % 10
return a1 * b1
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a1 = a % 10
let b1 = b % 10
return a1 * b1
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let first = a % 10
let second = b % 10
return first * second
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let first = a % 10
let second = b % 10
return first * second
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
let vowels = ["A", "E", "I", "O", "U"]
var count = 0
for (index, char) in s.enumerated() {
if vowels.contains(String(char)) && index % 2 == 0 {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let vowels = ["A", "E", "I", "O", "U"]
var count = 0
for (index, char) in s.enumerated() {
if vowels.contains(String(char)) && index % 2 == 0 {
count += 1
}
}
return count
}
```
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if index % 2 == 0 && char.isUppercase {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let value = Double(value)
let value = value!
let value = value.rounded()
let value = Int(value)
return 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 {
let value = Double(value)
let value = value!
let value = value.rounded()
let value = Int(value)
return value
}
```
let value = value! // invalid redeclaration of 'value'
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) < abs(roundedDown - number) {
return Int(roundedUp)
} else {
return Int(roundedDown)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) < abs(roundedDown - number) {
return Int(roundedUp)
} else {
return Int(roundedDown)
}
}
```
let rounded = round(number) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(number - roundedUp) < abs(number - roundedDown) {
return Int(roundedUp)
} else {
return Int(roundedDown)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(number - roundedUp) < abs(number - roundedDown) {
return Int(roundedUp)
} else {
return Int(roundedDown)
}
}
```
let rounded = round(number) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let value = Double(value)
let roundedValue = round(value!)
let roundedValueAwayFromZero = round(abs(value!))
if abs(value!) == roundedValueAwayFromZero {
return Int(roundedValueAwayFromZero)
} else {
return Int(roundedValue)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let value = Double(value)
let roundedValue = round(value!)
let roundedValueAwayFromZero = round(abs(value!))
if abs(value!) == roundedValueAwayFromZero {
return Int(roundedValueAwayFromZero)
} else {
return Int(roundedValue)
}
}
```
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) > abs(roundedDown - number) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) > abs(roundedDown - number) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```
let rounded = round(number) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(number - roundedUp) > abs(number - roundedDown) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(number - roundedUp) > abs(number - roundedDown) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```
let rounded = round(number) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) > abs(roundedDown - number) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) > abs(roundedDown - number) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```
let rounded = round(number) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let value = Double(value)!
let rounded = round(value)
let roundedUp = ceil(value)
let roundedDown = floor(value)
if abs(roundedUp - value) > abs(roundedDown - value) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let value = Double(value)!
let rounded = round(value)
let roundedUp = ceil(value)
let roundedDown = floor(value)
if abs(roundedUp - value) > abs(roundedDown - value) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```
let rounded = round(value) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) == abs(roundedDown - number) {
if roundedUp > roundedDown {
return Int(roundedUp)
} else {
return Int(roundedDown)
}
} else if abs(roundedUp - number) > abs(roundedDown - number) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) == abs(roundedDown - number) {
if roundedUp > roundedDown {
return Int(roundedUp)
} else {
return Int(roundedDown)
}
} else if abs(roundedUp - number) > abs(roundedDown - number) {
return Int(roundedDown)
} else {
return Int(roundedUp)
}
}
```
let rounded = round(number) // initialization of immutable value 'rounded' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) == abs(roundedDown - number) {
return Int(roundedUp)
}
return Int(rounded)
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Double(value)!
let rounded = round(number)
let roundedUp = ceil(number)
let roundedDown = floor(number)
if abs(roundedUp - number) == abs(roundedDown - number) {
return Int(roundedUp)
}
return Int(rounded)
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var currentLevel = n
for _ in 0..<n {
pile.append(currentLevel)
currentLevel = currentLevel % 2 == 0 ? currentLevel + 1 : currentLevel + 2
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var currentLevel = n
for _ in 0..<n {
pile.append(currentLevel)
currentLevel = currentLevel % 2 == 0 ? currentLevel + 1 : currentLevel + 2
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
var current = n
for _ in 0..<n {
result.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = n
for _ in 0..<n {
pile.append(current)
current = current % 2 == 0 ? current + 1 : current + 2
}
return pile
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = s.components(separatedBy: " ")
words = words.flatMap { $0.components(separatedBy: ",") }
return words
}
```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] {
var words = s.components(separatedBy: " ")
words = words.flatMap { $0.components(separatedBy: ",") }
return words
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = s.components(separatedBy: " ")
words.append(contentsOf: s.components(separatedBy: ","))
return words
}
```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] {
var words = s.components(separatedBy: " ")
words.append(contentsOf: s.components(separatedBy: ","))
return words
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = s.components(separatedBy: " ")
words = words.flatMap { $0.components(separatedBy: ",") }
return words
}
```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] {
var words = s.components(separatedBy: " ")
words = words.flatMap { $0.components(separatedBy: ",") }
return words
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = s.components(separatedBy: " ")
words = words.filter { $0 != "" }
return words
}
```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] {
var words = s.components(separatedBy: " ")
words = words.filter { $0 != "" }
return words
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = [String]()
let string = s.replacingOccurrences(of: ",", with: " ")
let string2 = string.components(separatedBy: " ")
for i in string2 {
if i != "" {
words.append(i)
}
}
return words
}
```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] {
var words = [String]()
let string = s.replacingOccurrences(of: ",", with: " ")
let string2 = string.components(separatedBy: " ")
for i in string2 {
if i != "" {
words.append(i)
}
}
return words
}
```
func wordsString(s: String) -> [String] {
var words = [String]()
let string = s.replacingOccurrences(of: ",", with: " ")
let stringArray = string.components(separatedBy: " ")
for word in stringArray {
if word != "" {
words.append(word)
}
}
return words
}
```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] {
var words = [String]()
let string = s.replacingOccurrences(of: ",", with: " ")
let stringArray = string.components(separatedBy: " ")
for word in stringArray {
if word != "" {
words.append(word)
}
}
return words
}
```
func wordsString(s: String) -> [String] {
var words = [String]()
let string = s.replacingOccurrences(of: ",", with: " ")
let string2 = string.components(separatedBy: " ")
for word in string2 {
if word != "" {
words.append(word)
}
}
return words
}
```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] {
var words = [String]()
let string = s.replacingOccurrences(of: ",", with: " ")
let string2 = string.components(separatedBy: " ")
for word in string2 {
if word != "" {
words.append(word)
}
}
return words
}
```
func wordsString(s: String) -> [String] {
var words = s.components(separatedBy: " ")
words.removeAll(where: { $0 == "" })
return words
}
```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] {
var words = s.components(separatedBy: " ")
words.removeAll(where: { $0 == "" })
return words
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = [String]()
let split = s.components(separatedBy: " ")
for i in split {
if i != "" {
words.append(i)
}
}
return words
}
```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] {
var words = [String]()
let split = s.components(separatedBy: " ")
for i in split {
if i != "" {
words.append(i)
}
}
return words
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
var words = [String]()
let split = s.components(separatedBy: " ")
for word in split {
if word != "" {
words.append(word)
}
}
return words
}
```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] {
var words = [String]()
let split = s.components(separatedBy: " ")
for word in split {
if word != "" {
words.append(word)
}
}
return words
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 && y % 2 == 0 {
return max(x, y)
} else if x % 2 == 0 && y % 2 != 0 {
return y
} else if x % 2 != 0 && y % 2 == 0 {
return x
} else {
return -1
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 && y % 2 == 0 {
return max(x, y)
} else if x % 2 == 0 && y % 2 != 0 {
return y
} else if x % 2 != 0 && y % 2 == 0 {
return x
} else {
return -1
}
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var maxEven = -1
for i in x...y {
if i % 2 == 0 {
maxEven = i
}
}
return maxEven
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var maxEven = -1
for i in x...y {
if i % 2 == 0 {
maxEven = i
}
}
return maxEven
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var even = x
if x % 2 == 0 {
while even <= y {
even += 2
}
return even - 2
} else {
while even <= y {
even += 2
}
return even - 2
}
}
```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 even = x
if x % 2 == 0 {
while even <= y {
even += 2
}
return even - 2
} else {
while even <= y {
even += 2
}
return even - 2
}
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var i = x
var j = y
if x > y {
let temp = i
i = j
j = temp
}
while i <= j {
if i % 2 == 0 {
return i
}
i += 1
}
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 {
var i = x
var j = y
if x > y {
let temp = i
i = j
j = temp
}
while i <= j {
if i % 2 == 0 {
return i
}
i += 1
}
return -1
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in x...y {
if i % 2 == 0 {
result = i
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 && y % 2 == 0 {
if x > y {
return y
} else {
return x
}
} else if x % 2 == 0 && y % 2 != 0 {
return x
} else if x % 2 != 0 && y % 2 == 0 {
return y
} else {
return -1
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 && y % 2 == 0 {
if x > y {
return y
} else {
return x
}
} else if x % 2 == 0 && y % 2 != 0 {
return x
} else if x % 2 != 0 && y % 2 == 0 {
return y
} else {
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> {
if n > m {
return .failure(-1)
}
let sum = (n...m).reduce(0, +)
let avg = Int(Double(sum) / Double(m - n + 1))
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = (n...m).reduce(0, +)
let avg = Int(Double(sum) / Double(m - n + 1))
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return .success(binary)
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return .success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let avg = Double(n + m) / 2
let rounded = Int(round(avg))
let binary = String(rounded, radix: 2)
return .success(binary)
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let avg = Double(n + m) / 2
let rounded = Int(round(avg))
let binary = String(rounded, radix: 2)
return .success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return .success(binary)
}
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 1 && s[s.index(after: s.startIndex)] == char {
return .success(index)
}
}
return .failure(-1)
}
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 2 && s[s.index(after: s.startIndex)] == char && s[s.index(after: s.index(after: s.startIndex))] == char {
return .success(index)
}
}
return .failure(-1)
}
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 3 && s[s.index(after: s.startIndex)] == char && s[s.index(after: s.index(after: s.startIndex))] == char && s[s.index(after: s.index(after: s.index(after: s.startIndex)))] == char {
return .success(index)
}
}
return .failure(-1)
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
let binary = String(avg, radix: 2)
return .success(binary)
}
// You are given a string s. Your task is to find the first occurrence of the
// character that appears twice in a row. If there is no such character, return
// -1.
// Example:
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abc") == .failure(-1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 1 && s[s.index(after: s.startIndex)] == char {
return .success(index)
}
}
return .failure(-1)
}
// You are given a string s. Your task is to find the first occurrence of the
// character that appears three times in a row. If there is no such character,
// return -1.
// Example:
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abc") == .failure(-1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 2 && s[s.index(after: s.startIndex)] == char && s[s.index(after: s.index(after: s.startIndex))] == char {
return .success(index)
}
}
return .failure(-1)
}
// You are given a string s. Your task is to find the first occurrence of the
// character that appears four times in a row. If there is no such character,
// return -1.
// Example:
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abc") == .failure(-1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 3 && s[s.index(after: s.startIndex)] == char && s[s.index(after: s.index(after: s.startIndex))] == char && s[s.index(after: s.index(after: s.index(after: s.startIndex)))] == char {
return .success(index)
}
}
return .failure(-1)
}
// You are given a string s. Your task is to find the first occurrence of the
// character that appears five times in a row. If there is no such character,
// return -1.
// Example:
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abc") == .failure(-1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
// firstRepeatedCharacter(s: "abccba") == .success(1)
func firstRepeatedCharacter(s: String) -> Result<Int, Int> {
for (index, char) in s.enumerated() {
if index < s.count - 4 && s[s.index(after: s.startIndex)] == char && s[s.index(after: s.index(after: s.startIndex))] == char && s[s.index(after: s.index(after: s.index(after: s.startIndex)))] == char && s[s.index(after: s.index(after: s.index(after: s.index(after: s.startIndex))))] == char {
return .success(
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func firstRepeatedCharacter(s: String) -> Result<Int, Int> { // invalid redeclaration of 'firstRepeatedCharacter(s:)'
func firstRepeatedCharacter(s: String) -> Result<Int, Int> { // invalid redeclaration of 'firstRepeatedCharacter(s:)'
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(0) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(0) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(1) }
let sum = (n...m).reduce(0, +)
let avg = sum / (m - n + 1)
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func uniqueDigits(x: [Int]) -> [Int] {
var result: [Int] = []
for i in x {
var temp = i
var flag = true
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
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 {
var temp = i
var flag = true
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
result.append(i)
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
var flag = false
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = true
break
}
temp = temp / 10
}
if !flag {
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 {
var temp = i
var flag = false
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = true
break
}
temp = temp / 10
}
if !flag {
result.append(i)
}
}
return result.sorted()
}
```
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()
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var number = i
var hasEven = false
while number > 0 {
let digit = number % 10
if digit % 2 == 0 {
hasEven = true
break
}
number /= 10
}
if !hasEven {
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 {
var number = i
var hasEven = false
while number > 0 {
let digit = number % 10
if digit % 2 == 0 {
hasEven = true
break
}
number /= 10
}
if !hasEven {
result.append(i)
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp = temp / 10
}
if flag {
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 {
var temp = i
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp = temp / 10
}
if flag {
result.append(i)
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp = temp / 10
}
if flag {
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 {
var temp = i
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp = temp / 10
}
if flag {
result.append(i)
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
var temp = i
while temp > 0 {
if temp % 10 % 2 == 0 {
break
}
temp = temp / 10
}
if temp == 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 {
var temp = i
while temp > 0 {
if temp % 10 % 2 == 0 {
break
}
temp = temp / 10
}
if temp == 0 {
result.append(i)
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var arr = [Int]()
for i in x {
if i % 2 != 0 {
arr.append(i)
}
}
return arr.sorted()
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var arr = [Int]()
for i in x {
if i % 2 != 0 {
arr.append(i)
}
}
return arr.sorted()
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var arr = [Int]()
for i in x {
if i % 2 != 0 {
arr.append(i)
}
}
return arr.sorted()
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var arr = [Int]()
for i in x {
if i % 2 != 0 {
arr.append(i)
}
}
return arr.sorted()
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result: [Int] = []
for i in x {
var temp = i
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
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 {
var temp = i
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
result.append(i)
}
}
return result.sorted()
}
```
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr = arr.map { String($0) }
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") }
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") }
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") }
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") }
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") }
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") }
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") }
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") }
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") }
arr.reverse()
return arr
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr = arr.map { String($0) }
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") }
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") }
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") }
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") }
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") }
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") }
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") }
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") }
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") }
arr.reverse()
return arr
}
```
arr = arr.map { String($0) } // cannot convert value of type 'String' to closure result type 'Int'
arr = arr.map { $0.replacingOccurrences(of: "1", with: "One") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "2", with: "Two") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "3", with: "Three") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "4", with: "Four") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "5", with: "Five") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "6", with: "Six") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "7", with: "Seven") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "8", with: "Eight") } // value of type 'Int' has no member 'replacingOccurrences'
arr = arr.map { $0.replacingOccurrences(of: "9", with: "Nine") } // value of type 'Int' has no member 'replacingOccurrences'
return arr // cannot convert return expression of type '[Int]' to return type '[String]'
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr = arr.reversed()
var result = [String]()
for num in arr {
switch num {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr = arr.reversed()
var result = [String]()
for num in arr {
switch num {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(i.description)
}
}
result.sort(by: { $0.count > $1.count })
result.reverse()
for i in 0..<result.count {
switch result[i] {
case "1":
result[i] = "One"
case "2":
result[i] = "Two"
case "3":
result[i] = "Three"
case "4":
result[i] = "Four"
case "5":
result[i] = "Five"
case "6":
result[i] = "Six"
case "7":
result[i] = "Seven"
case "8":
result[i] = "Eight"
case "9":
result[i] = "Nine"
default:
break
}
}
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(i.description)
}
}
result.sort(by: { $0.count > $1.count })
result.reverse()
for i in 0..<result.count {
switch result[i] {
case "1":
result[i] = "One"
case "2":
result[i] = "Two"
case "3":
result[i] = "Three"
case "4":
result[i] = "Four"
case "5":
result[i] = "Five"
case "6":
result[i] = "Six"
case "7":
result[i] = "Seven"
case "8":
result[i] = "Eight"
case "9":
result[i] = "Nine"
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr.reverse()
var result = [String]()
for i in arr {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr.reverse()
var result = [String]()
for i in arr {
switch i {
case 1:
result.append("One")
case 2:
result.append("Two")
case 3:
result.append("Three")
case 4:
result.append("Four")
case 5:
result.append("Five")
case 6:
result.append("Six")
case 7:
result.append("Seven")
case 8:
result.append("Eight")
case 9:
result.append("Nine")
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let numbers = arr.filter { $0 > 0 && $0 < 10 }
let sorted = numbers.sorted(by: >)
return sorted.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] {
let numbers = arr.filter { $0 > 0 && $0 < 10 }
let sorted = numbers.sorted(by: >)
return sorted.map { String($0) }
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var arr = arr
var result = [String]()
for i in 0..<arr.count {
if arr[i] > 0 && arr[i] < 10 {
result.append(String(arr[i]))
}
}
result = result.sorted(by: { $0.count > $1.count })
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var arr = arr
var result = [String]()
for i in 0..<arr.count {
if arr[i] > 0 && arr[i] < 10 {
result.append(String(arr[i]))
}
}
result = result.sorted(by: { $0.count > $1.count })
return result
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr = arr.map { String($0) }
arr = arr.map {
switch $0 {
case "1":
return "One"
case "2":
return "Two"
case "3":
return "Three"
case "4":
return "Four"
case "5":
return "Five"
case "6":
return "Six"
case "7":
return "Seven"
case "8":
return "Eight"
case "9":
return "Nine"
default:
return ""
}
}
return arr
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 > $1 })
arr = arr.map { String($0) }
arr = arr.map {
switch $0 {
case "1":
return "One"
case "2":
return "Two"
case "3":
return "Three"
case "4":
return "Four"
case "5":
return "Five"
case "6":
return "Six"
case "7":
return "Seven"
case "8":
return "Eight"
case "9":
return "Nine"
default:
return ""
}
}
return arr
}
```
arr = arr.map { String($0) } // cannot convert value of type 'String' to closure result type 'Int'
case "1": // expression pattern of type 'String' cannot match values of type 'Int'
return arr // cannot convert return expression of type '[Int]' to return type '[String]'
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(i.description)
}
}
result = result.sorted(by: { $0.count < $1.count })
result = result.reversed()
for i in 0..<result.count {
result[i] = result[i].uppercased()
}
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(i.description)
}
}
result = result.sorted(by: { $0.count < $1.count })
result = result.reversed()
for i in 0..<result.count {
result[i] = result[i].uppercased()
}
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 < $1 })
arr.reverse()
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
return arr.map { names[$0 - 1] }
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var arr = arr
arr = arr.filter { $0 > 0 && $0 < 10 }
arr.sort(by: { $0 < $1 })
arr.reverse()
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
return arr.map { names[$0 - 1] }
}
```
func byLength(arr: [Int]) -> [String] {
let numbers = arr.filter { $0 > 0 && $0 < 10 }
let sorted = numbers.sorted { $0 > $1 }
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
let result = sorted.map { names[$0 - 1] }
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
let numbers = arr.filter { $0 > 0 && $0 < 10 }
let sorted = numbers.sorted { $0 > $1 }
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
let result = sorted.map { names[$0 - 1] }
return result
}
```
func f(n: Int) -> [Int] {
var arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(factorial(i))
} else {
arr.append(sum(i))
}
}
return arr
}
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 arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(factorial(i))
} else {
arr.append(sum(i))
}
}
return arr
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var array = [Int]()
for i in 1...n {
if i % 2 == 0 {
array.append(i)
} else {
var sum = 0
for j in 1...i {
sum += j
}
array.append(sum)
}
}
return array
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var array = [Int]()
for i in 1...n {
if i % 2 == 0 {
array.append(i)
} else {
var sum = 0
for j in 1...i {
sum += j
}
array.append(sum)
}
}
return array
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
print(f(n: 5))
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial: Int = 1
for j in 1...i {
factorial *= j
}
result.append(factorial)
} else {
var sum: Int = 0
for j in 1...i {
sum += j
}
result.append(sum)
}
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial: Int = 1
for j in 1...i {
factorial *= j
}
result.append(factorial)
} else {
var sum: Int = 0
for j in 1...i {
sum += j
}
result.append(sum)
}
}
return result
}
```
func f(n: Int) -> [Int] {
var arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(factorial(i))
} else {
arr.append(sum(i))
}
}
return arr
}
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 arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(factorial(i))
} else {
arr.append(sum(i))
}
}
return arr
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
print(f(n: 5))
```
func f(n: Int) -> [Int] {
var arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(factorial(i))
} else {
arr.append(sum(i))
}
}
return arr
}
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 arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(factorial(i))
} else {
arr.append(sum(i))
}
}
return arr
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(i)
} else {
var sum = 0
for j in 1...i {
sum += j
}
arr.append(sum)
}
}
return arr
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var arr = [Int]()
for i in 1...n {
if i % 2 == 0 {
arr.append(i)
} else {
var sum = 0
for j in 1...i {
sum += j
}
arr.append(sum)
}
}
return arr
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial: Int = 1
for j in 1...i {
factorial *= j
}
result.append(factorial)
} else {
var sum: Int = 0
for j in 1...i {
sum += j
}
result.append(sum)
}
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
var factorial: Int = 1
for j in 1...i {
factorial *= j
}
result.append(factorial)
} else {
var sum: Int = 0
for j in 1...i {
sum += j
}
result.append(sum)
}
}
return result
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
if isPalindrome(i) { // cannot find 'isPalindrome' in scope
func evenOddPalindrome(n: Int) -> (Int, Int) {
var countEven = 0
var countOdd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
countEven += 1
} else {
countOdd += 1
}
}
}
return (countEven, countOdd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let strRev = String(str.reversed())
return str == strRev
}
```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 countEven = 0
var countOdd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
countEven += 1
} else {
countOdd += 1
}
}
}
return (countEven, countOdd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let strRev = String(str.reversed())
return str == strRev
}
evenOddPalindrome(n: 3)
evenOddPalindrome(n: 12)
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if i == reverse(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if i == reverse(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```
if i == reverse(i) { // cannot find 'reverse' in scope
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let rev = String(str.reversed())
return str == rev
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let rev = String(str.reversed())
return str == rev
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let rev = String(str.reversed())
return str == rev
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let rev = String(str.reversed())
return str == rev
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let s = String(n)
let r = String(s.reversed())
return s == r
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let s = String(n)
let r = String(s.reversed())
return s == r
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let reversed = String(str.reversed())
return str == reversed
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let reversed = String(str.reversed())
return str == reversed
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return (count / 2, count - count / 2)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let reversedStr = String(str.reversed())
return str == reversedStr
}
```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 count = 0
for i in 1...n {
if isPalindrome(i) {
count += 1
}
}
return (count / 2, count - count / 2)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let reversedStr = String(str.reversed())
return str == reversedStr
}
```
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let rev = String(str.reversed())
return str == rev
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
let str = String(n)
let rev = String(str.reversed())
return str == rev
}
```
```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 count = 0
var count2 = 0
for i in 1...n {
if i == 1 {
count += 1
count2 += 1
} else if i == 2 {
count += 1
count2 += 1
} else if i == 3 {
count += 1
count2 += 1
} else if i == 4 {
count += 1
count2 += 1
} else if i == 5 {
count += 1
count2 += 1
} else if i == 6 {
count += 1
count2 += 1
} else if i == 7 {
count += 1
count2 += 1
} else if i == 8 {
count += 1
count2 += 1
} else if i == 9 {
count += 1
count2 += 1
} else if i == 11 {
count += 1
count2 += 1
} else if i == 101 {
count += 1
count2 += 1
} else if i == 111 {
count += 1
count2 += 1
} else if i == 121 {
count += 1
count2 += 1
} else if i == 131 {
count += 1
count2 += 1
} else if i == 141 {
count += 1
count2 += 1
} else if i == 151 {
count += 1
count2 += 1
} else if i == 161 {
count += 1
count2 += 1
} else if i == 171 {
count += 1
count2 += 1
} else if i == 181 {
count += 1
count2 += 1
} else if i == 191 {
count += 1
count2 += 1
} else if i == 1001 {
count += 1
count2 += 1
} else if i == 1101 {
count += 1
count2 += 1
} else if i == 1111 {
count += 1
count2 += 1
} else if i == 1121 {
count += 1
count2 += 1
} else if i == 1131 {
count += 1
count2 += 1
} else if i == 1141 {
count += 1
count2 += 1
} else if i == 1151 {
count += 1
count2 += 1
} else if i == 1161 {
count += 1
count2 += 1
} else if i == 1171 {
count += 1
count2 += 1
} else if i == 1181 {
count += 1
count2 += 1
} else if i == 1191 {
count += 1
count2 += 1
} else if i == 10001 {
count += 1
count2 += 1
} else if i == 10101 {
count += 1
count2 += 1
} else if i == 10201 {
count += 1
count2 += 1
} else if i == 10301 {
count += 1
count2 += 1
} else if i == 10401 {
count += 1
count2 += 1
} else if i == 10501 {
count += 1
count2 += 1
} else if i == 10601 {
count += 1
count2 += 1
} else if i == 10701 {
count += 1
count2 += 1
} else if i == 10801 {
count +=
XCTAssertTrue(evenOddPalindrome(n: 123) == (8, 13)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 12) == (4, 6)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 3) == (1, 2)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 63) == (6, 8)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 25) == (5, 6)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 19) == (4, 6)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 9) == (4, 5)) // cannot find 'evenOddPalindrome' in scope
XCTAssertTrue(evenOddPalindrome(n: 1) == (0, 1)) // cannot find 'evenOddPalindrome' in scope
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 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 {
count += 1
} else if num < 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if sumOfDigits(num: num) > 0 {
count += 1
}
}
return count
}
func sumOfDigits(num: Int) -> Int {
var num = num
var sum = 0
while num != 0 {
sum += abs(num % 10)
num /= 10
}
return sum
}
```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 sumOfDigits(num: num) > 0 {
count += 1
}
}
return count
}
func sumOfDigits(num: Int) -> Int {
var num = num
var sum = 0
while num != 0 {
sum += abs(num % 10)
num /= 10
}
return sum
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var currentNum = abs(num)
while currentNum > 0 {
sum += currentNum % 10
currentNum = currentNum / 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 currentNum = abs(num)
while currentNum > 0 {
sum += currentNum % 10
currentNum = currentNum / 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 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 {
count += 1
} else if num < 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += abs(n % 10)
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += abs(n % 10)
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var currentNum = abs(num)
while currentNum > 0 {
sum += currentNum % 10
currentNum /= 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 currentNum = abs(num)
while currentNum > 0 {
sum += currentNum % 10
currentNum /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 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 {
count += 1
} else if num < 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 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 {
count += 1
} else if num < 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
let digits = String(num).map { Int(String($0))! }
let sum = digits.reduce(0, +)
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
let digits = String(num).map { Int(String($0))! }
let sum = digits.reduce(0, +)
if sum > 0 {
count += 1
}
}
return count
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += abs(n % 10)
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += abs(n % 10)
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 0 else { return true }
var arr = arr
var i = 0
while i < arr.count {
if i < arr.count - 1 && arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 0 else { return true }
var arr = arr
var i = 0
while i < arr.count {
if i < arr.count - 1 && arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
if arr.isEmpty {
return true
}
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
if arr.isEmpty {
return true
}
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.append(arr.remove(at: i))
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
guard arr.count > 1 else { return true }
var arr = arr
var i = 0
while i < arr.count - 1 {
if arr[i] > arr[i + 1] {
arr.insert(arr.removeLast(), at: 0)
i = 0
} else {
i += 1
}
}
return arr == arr.sorted()
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst2[i] = lst1[i]
lst1[i] = 0
count += 1
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 0 {
lst1[i] = lst2[i]
lst2[i] = 0
count += 1
}
}
if count == lst1.count {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst2[i] = lst1[i]
lst1[i] = 0
count += 1
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 0 {
lst1[i] = lst2[i]
lst2[i] = 0
count += 1
}
}
if count == lst1.count {
return "YES"
} else {
return "NO"
}
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1.remove(at: i)
lst2.remove(at: i)
count += 1
}
}
if lst1.count == 0 {
return "YES"
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 0 {
lst1.append(lst2[i])
lst2.remove(at: i)
count += 1
}
}
if lst1.count == 0 {
return "YES"
}
if lst1.count == count {
return "YES"
}
return "NO"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1.remove(at: i)
lst2.remove(at: i)
count += 1
}
}
if lst1.count == 0 {
return "YES"
}
for i in 0..<lst2.count {
if lst2[i] % 2 == 0 {
lst1.append(lst2[i])
lst2.remove(at: i)
count += 1
}
}
if lst1.count == 0 {
return "YES"
}
if lst1.count == count {
return "YES"
}
return "NO"
}
```
// Fatal error: Index out of range
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
}
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[i]
}
}
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
}
return "NO"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
}
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[i]
}
}
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
}
return "NO"
}
```
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var even = 0
var odd = 0
for i in lst1 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
for i in lst2 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
if even > odd {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var even = 0
var odd = 0
for i in lst1 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
for i in lst2 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
if even > odd {
return "YES"
} else {
return "NO"
}
}
```
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[i]
}
}
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1[i] = lst2[i]
}
}
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
return "NO"
}
}
return "YES"
}
```
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var even = 0
var odd = 0
for i in lst1 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
for i in lst2 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
if even == lst1.count || even == lst2.count {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var even = 0
var odd = 0
for i in lst1 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
for i in lst2 {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
if even == lst1.count || even == lst2.count {
return "YES"
} else {
return "NO"
}
}
```
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
let temp = lst1[i]
lst1[i] = lst2[j]
lst2[j] = temp
i += 1
j += 1
} else {
j += 1
}
}
return lst1.allSatisfy { $0 % 2 == 0 } ? "YES" : "NO"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
let temp = lst1[i]
lst1[i] = lst2[j]
lst2[j] = temp
i += 1
j += 1
} else {
j += 1
}
}
return lst1.allSatisfy { $0 % 2 == 0 } ? "YES" : "NO"
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
}
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 != 0 && lst2[j] % 2 == 0 {
let temp = lst1[i]
lst1[i] = lst2[j]
lst2[j] = temp
}
}
}
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
}
for i in 0..<lst1.count {
for j in 0..<lst2.count {
if lst1[i] % 2 != 0 && lst2[j] % 2 == 0 {
let temp = lst1[i]
lst1[i] = lst2[j]
lst2[j] = temp
}
}
}
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
return "NO"
}
}
return "YES"
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst2.append(lst1[i])
lst1.remove(at: i)
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 != 0 {
lst1.append(lst2[i])
lst2.remove(at: i)
}
}
if lst1.count == 0 {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst2.append(lst1[i])
lst1.remove(at: i)
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 != 0 {
lst1.append(lst2[i])
lst2.remove(at: i)
}
}
if lst1.count == 0 {
return "YES"
} else {
return "NO"
}
}
```
// Fatal error: Index out of range
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
let temp = lst1[i]
lst1[i] = lst2[j]
lst2[j] = temp
i += 1
j += 1
} else {
j += 1
}
}
return lst1.allSatisfy { $0 % 2 == 0 } ? "YES" : "NO"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
let temp = lst1[i]
lst1[i] = lst2[j]
lst2[j] = temp
i += 1
j += 1
} else {
j += 1
}
}
return lst1.allSatisfy { $0 % 2 == 0 } ? "YES" : "NO"
}
```
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
var count = 0
var maxCount = 0
var maxLetter = ""
for letter in test.characters {
if let value = result[String(letter)] {
result[String(letter)] = value + 1
} else {
result[String(letter)] = 1
}
}
for (key, value) in result {
if value > maxCount {
maxCount = value
maxLetter = key
}
}
for (key, value) in result {
if value == maxCount {
count += 1
}
}
if count > 1 {
return result
} else {
return [maxLetter : maxCount]
}
}
```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 count = 0
var maxCount = 0
var maxLetter = ""
for letter in test.characters {
if let value = result[String(letter)] {
result[String(letter)] = value + 1
} else {
result[String(letter)] = 1
}
}
for (key, value) in result {
if value > maxCount {
maxCount = value
maxLetter = key
}
}
for (key, value) in result {
if value == maxCount {
count += 1
}
}
if count > 1 {
return result
} else {
return [maxLetter : maxCount]
}
}
```
for letter in test.characters { // 'characters' is unavailable: Please use String directly
for (key, value) in result { // immutable value 'key' was never used; consider replacing with '_' or removing it
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
var count = 0
var max = 0
var maxKey = ""
for (index, char) in test.characters.enumerate() {
if index == test.characters.count - 1 {
if let value = result[String(char)] {
result[String(char)] = value + 1
} else {
result[String(char)] = 1
}
} else {
if let value = result[String(char)] {
result[String(char)] = value + 1
} else {
result[String(char)] = 1
}
}
}
for (key, value) in result {
if value > max {
max = value
maxKey = key
}
}
for (key, value) in result {
if value == max {
count += 1
}
}
if count > 1 {
return result
} else {
return [maxKey : max]
}
}
```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 count = 0
var max = 0
var maxKey = ""
for (index, char) in test.characters.enumerate() {
if index == test.characters.count - 1 {
if let value = result[String(char)] {
result[String(char)] = value + 1
} else {
result[String(char)] = 1
}
} else {
if let value = result[String(char)] {
result[String(char)] = value + 1
} else {
result[String(char)] = 1
}
}
}
for (key, value) in result {
if value > max {
max = value
maxKey = key
}
}
for (key, value) in result {
if value == max {
count += 1
}
}
if count > 1 {
return result
} else {
return [maxKey : max]
}
}
```
for (index, char) in test.characters.enumerate() { // value of type 'String' has no member 'enumerate'
func histogram(test: String) -> [String : Int] {
let words = test.components(separatedBy: " ")
var dict = [String : Int]()
for word in words {
if let count = dict[word] {
dict[word] = count + 1
} else {
dict[word] = 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let words = test.components(separatedBy: " ")
var dict = [String : Int]()
for word in words {
if let count = dict[word] {
dict[word] = count + 1
} else {
dict[word] = 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 arr = test.components(separatedBy: " ")
for i in arr {
if let count = dict[i] {
dict[i] = count + 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 count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
let words = test.components(separatedBy: " ")
var dict = [String : Int]()
for word in words {
if let count = dict[word] {
dict[word] = count + 1
} else {
dict[word] = 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let words = test.components(separatedBy: " ")
var dict = [String : Int]()
for word in words {
if let count = dict[word] {
dict[word] = count + 1
} else {
dict[word] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
let letters = test.components(separatedBy: " ")
var dictionary = [String : Int]()
for letter in letters {
if dictionary[letter] != nil {
dictionary[letter]! += 1
} else {
dictionary[letter] = 1
}
}
return dictionary
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let letters = test.components(separatedBy: " ")
var dictionary = [String : Int]()
for letter in letters {
if dictionary[letter] != nil {
dictionary[letter]! += 1
} else {
dictionary[letter] = 1
}
}
return dictionary
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
var max = 0
for i in test.characters {
let count = test.characters.filter { $0 == i }.count
if count > max {
max = count
}
dict[String(i)] = count
}
return dict.filter { $0.1 == max }
}
```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
for i in test.characters {
let count = test.characters.filter { $0 == i }.count
if count > max {
max = count
}
dict[String(i)] = count
}
return dict.filter { $0.1 == max }
}
```
for i in test.characters { // 'characters' is unavailable: Please use String directly
let count = test.characters.filter { $0 == i }.count // 'characters' is unavailable: Please use String directly
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let arr = test.components(separatedBy: " ")
for i in arr {
if let count = dict[i] {
dict[i] = count + 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 count = dict[i] {
dict[i] = count + 1
} else {
dict[i] = 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var result = [String : Int]()
var count = 0
var max = 0
var maxKey = ""
var arr = test.components(separatedBy: " ")
for i in arr {
if result[i] != nil {
result[i]! += 1
} else {
result[i] = 1
}
}
for (key, value) in result {
if value > max {
max = value
maxKey = key
}
}
for (key, value) in result {
if value == max {
result[key] = value
}
}
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 count = 0
var max = 0
var maxKey = ""
var arr = test.components(separatedBy: " ")
for i in arr {
if result[i] != nil {
result[i]! += 1
} else {
result[i] = 1
}
}
for (key, value) in result {
if value > max {
max = value
maxKey = key
}
}
for (key, value) in result {
if value == max {
result[key] = value
}
}
return result
}
```
var count = 0 // initialization of variable 'count' was never used; consider replacing with assignment to '_' or removing it
var maxKey = "" // variable 'maxKey' was written to, but never read
var arr = test.components(separatedBy: " ") // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.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 = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.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 = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
if result == String(result.reversed()) {
return (result, true)
} else {
return (result, false)
}
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
if result == String(result.reversed()) {
return (result, true)
} else {
return (result, false)
}
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.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 = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, result == String(result.reversed()))
}
```
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
var isPalindrome = true
for i in 0..<result.count/2 {
if result[result.index(result.startIndex, offsetBy: i)] != result[result.index(result.startIndex, offsetBy: result.count - i - 1)] {
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 = ""
for i in s {
if !c.contains(i) {
result += String(i)
}
}
var isPalindrome = true
for i in 0..<result.count/2 {
if result[result.index(result.startIndex, offsetBy: i)] != result[result.index(result.startIndex, offsetBy: result.count - i - 1)] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, str) in lst.enumerated() {
var count = 0
for char in str {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, str) in lst.enumerated() {
var count = 0
for char in str {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
for (index, str) in lst.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, string) in lst.enumerated() {
let count = string.reduce(0) { (result, char) -> Int in
let digit = Int(String(char))!
return digit % 2 == 1 ? result + 1 : result
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, string) in lst.enumerated() {
let count = string.reduce(0) { (result, char) -> Int in
let digit = Int(String(char))!
return digit % 2 == 1 ? result + 1 : result
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
for (index, string) in lst.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result: [String] = []
for (index, string) in lst.enumerated() {
var count = 0
for char in string {
if Int(String(char))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
for (index, string) in lst.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(String(j))! % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
for j in i..<nums.count {
var sum = 0
for k in i...j {
sum += nums[k]
}
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
for j in i..<nums.count {
var sum = 0
for k in i...j {
sum += nums[k]
}
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
for i in 0..<nums.count {
var sum = 0
for j in i..<nums.count {
sum += nums[j]
minSum = min(minSum, sum)
}
}
return minSum
}
```
func maxFill(grid: [[Int]], capacity: Int) -> Int {
}
```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 {
}
```
} // missing return in global function expected to return 'Int'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let rows = grid.count
let cols = grid[0].count
var result = 0
var visited = Array(repeating: Array(repeating: false, count: cols), count: rows)
func dfs(_ row: Int, _ col: Int, _ capacity: Int) {
if row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || grid[row][col] == 0 {
return
}
visited[row][col] = true
if grid[row][col] == 1 {
result += capacity
grid[row][col] = 0
}
dfs(row - 1, col, capacity)
dfs(row + 1, col, capacity)
dfs(row, col - 1, capacity)
dfs(row, col + 1, capacity)
}
for row in 0..<rows {
for col in 0..<cols {
if grid[row][col] == 1 {
dfs(row, col, capacity)
}
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let rows = grid.count
let cols = grid[0].count
var result = 0
var visited = Array(repeating: Array(repeating: false, count: cols), count: rows)
func dfs(_ row: Int, _ col: Int, _ capacity: Int) {
if row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || grid[row][col] == 0 {
return
}
visited[row][col] = true
if grid[row][col] == 1 {
result += capacity
grid[row][col] = 0
}
dfs(row - 1, col, capacity)
dfs(row + 1, col, capacity)
dfs(row, col - 1, capacity)
dfs(row, col + 1, capacity)
}
for row in 0..<rows {
for col in 0..<cols {
if grid[row][col] == 1 {
dfs(row, col, capacity)
}
}
}
return result
}
```
grid[row][col] = 0 // cannot assign through subscript: 'grid' is a 'let' constant
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let rows = grid.count
let cols = grid[0].count
var result = 0
for row in 0..<rows {
for col in 0..<cols {
if grid[row][col] == 1 {
result += capacity
}
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let rows = grid.count
let cols = grid[0].count
var result = 0
for row in 0..<rows {
for col in 0..<cols {
if grid[row][col] == 1 {
result += capacity
}
}
}
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
while capacity > 0 {
for row in grid {
for (index, value) in row.enumerated() {
if value == 1 {
if index > 0 && row[index - 1] == 0 {
grid[row.index(of: 1)!][index - 1] = 1
capacity -= 1
}
if index < row.count - 1 && row[index + 1] == 0 {
grid[row.index(of: 1)!][index + 1] = 1
capacity -= 1
}
if index > 0 && grid[row.index(of: 1)! - 1][index] == 0 {
grid[row.index(of: 1)! - 1][index] = 1
capacity -= 1
}
if index < row.count - 1 && grid[row.index(of: 1)! + 1][index] == 0 {
grid[row.index(of: 1)! + 1][index] = 1
capacity -= 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 grid = grid
var capacity = capacity
while capacity > 0 {
for row in grid {
for (index, value) in row.enumerated() {
if value == 1 {
if index > 0 && row[index - 1] == 0 {
grid[row.index(of: 1)!][index - 1] = 1
capacity -= 1
}
if index < row.count - 1 && row[index + 1] == 0 {
grid[row.index(of: 1)!][index + 1] = 1
capacity -= 1
}
if index > 0 && grid[row.index(of: 1)! - 1][index] == 0 {
grid[row.index(of: 1)! - 1][index] = 1
capacity -= 1
}
if index < row.count - 1 && grid[row.index(of: 1)! + 1][index] == 0 {
grid[row.index(of: 1)! + 1][index] = 1
capacity -= 1
}
}
}
}
result += 1
}
return result
}
```
grid[row.index(of: 1)!][index - 1] = 1 // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
grid[row.index(of: 1)!][index + 1] = 1 // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
if index > 0 && grid[row.index(of: 1)! - 1][index] == 0 { // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
grid[row.index(of: 1)! - 1][index] = 1 // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
if index < row.count - 1 && grid[row.index(of: 1)! + 1][index] == 0 { // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
grid[row.index(of: 1)! + 1][index] = 1 // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// Fatal error: Index out of range
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var grid = grid
var result = 0
while grid.contains(where: { $0.contains(1) }) {
for (i, row) in grid.enumerated() {
for (j, well) in row.enumerated() {
if well == 1 {
let min = min(capacity, row.filter { $0 == 1 }.count)
grid[i][j] = 0
result += min
}
}
}
}
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 grid = grid
var result = 0
while grid.contains(where: { $0.contains(1) }) {
for (i, row) in grid.enumerated() {
for (j, well) in row.enumerated() {
if well == 1 {
let min = min(capacity, row.filter { $0 == 1 }.count)
grid[i][j] = 0
result += min
}
}
}
}
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
for row in grid {
for well in row {
if well == 1 {
result += capacity
}
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
for row in grid {
for well in row {
if well == 1 {
result += capacity
}
}
}
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
var capacity = capacity
while capacity > 0 {
var row = 0
var column = 0
var max = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
row = i
column = j
max = 1
break
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i < row {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i > row {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if j < column {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if j > column {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i == row && j == column {
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i == row && j == column {
grid[i][j] = 0
capacity -= 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 grid = grid
var capacity = capacity
while capacity > 0 {
var row = 0
var column = 0
var max = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
row = i
column = j
max = 1
break
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i < row {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i > row {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if j < column {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if j > column {
row = i
column = j
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i == row && j == column {
max = 1
}
}
}
}
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
if i == row && j == column {
grid[i][j] = 0
capacity -= 1
result += 1
}
}
}
}
}
return result
}
```
var max = 0 // variable 'max' was written to, but never read
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var current = 0
var currentCapacity = capacity
var currentRow = 0
var currentCol = 0
var currentRowLength = grid[0].count
var currentRowCapacity = 0
while current < grid.count * grid[0].count {
if currentRowCapacity == 0 {
currentRowCapacity = currentRowLength
currentCol = 0
}
if grid[currentRow][currentCol] == 1 {
currentCapacity -= 1
currentRowCapacity -= 1
current += 1
}
if currentCapacity == 0 {
currentCapacity = capacity
currentRow += 1
currentRowCapacity = currentRowLength
}
currentCol += 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 current = 0
var currentCapacity = capacity
var currentRow = 0
var currentCol = 0
var currentRowLength = grid[0].count
var currentRowCapacity = 0
while current < grid.count * grid[0].count {
if currentRowCapacity == 0 {
currentRowCapacity = currentRowLength
currentCol = 0
}
if grid[currentRow][currentCol] == 1 {
currentCapacity -= 1
currentRowCapacity -= 1
current += 1
}
if currentCapacity == 0 {
currentCapacity = capacity
currentRow += 1
currentRowCapacity = currentRowLength
}
currentCol += 1
result += 1
}
return result
}
```
var currentRowLength = grid[0].count // variable 'currentRowLength' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var grid = grid
while grid.contains(where: { $0.contains(1) }) {
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
var count = 0
for k in 0..<grid.count {
if grid[k][j] == 1 {
count += 1
}
}
if count <= capacity {
for k in 0..<grid.count {
grid[k][j] = 0
}
result += count
} else {
for k in 0..<grid.count {
if grid[k][j] == 1 {
grid[k][j] = 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 grid = grid
while grid.contains(where: { $0.contains(1) }) {
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
var count = 0
for k in 0..<grid.count {
if grid[k][j] == 1 {
count += 1
}
}
if count <= capacity {
for k in 0..<grid.count {
grid[k][j] = 0
}
result += count
} else {
for k in 0..<grid.count {
if grid[k][j] == 1 {
grid[k][j] = 0
result += 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 current<bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos><bos>
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] {
var arr = arr
arr.sort { (a, b) -> Bool in
let a = a.toBinary().filter { $0 == "1" }.count
let b = b.toBinary().filter { $0 == "1" }.count
if a == b {
return a < b
} else {
return a > b
}
}
return arr
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort { (a, b) -> Bool in
let a = a.toBinary().filter { $0 == "1" }.count
let b = b.toBinary().filter { $0 == "1" }.count
if a == b {
return a < b
} else {
return a > b
}
}
return arr
}
```
let a = a.toBinary().filter { $0 == "1" }.count // value of type 'Int' has no member 'toBinary'
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.sorted {
let count1 = String($0, radix: 2).filter { $0 == "1" }.count
let count2 = String($1, radix: 2).filter { $0 == "1" }.count
if count1 == count2 {
return $0 < $1
} else {
return count1 < count2
}
}
return arr.map { $0 >= 0 ? $0 : -$0 }
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.sorted {
let count1 = String($0, radix: 2).filter { $0 == "1" }.count
let count2 = String($1, radix: 2).filter { $0 == "1" }.count
if count1 == count2 {
return $0 < $1
} else {
return count1 < count2
}
}
return arr.map { $0 >= 0 ? $0 : -$0 }
}
```
let arr = arr.sorted { // invalid redeclaration of 'arr'
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.sorted {
let first = String($0, radix: 2)
let second = String($1, radix: 2)
if first.filter { $0 == "1" }.count == second.filter { $0 == "1" }.count {
return $0 < $1
}
return first.filter { $0 == "1" }.count < second.filter { $0 == "1" }.count
}
return arr.map { $0 >= 0 ? $0 : -$0 }
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.sorted {
let first = String($0, radix: 2)
let second = String($1, radix: 2)
if first.filter { $0 == "1" }.count == second.filter { $0 == "1" }.count {
return $0 < $1
}
return first.filter { $0 == "1" }.count < second.filter { $0 == "1" }.count
}
return arr.map { $0 >= 0 ? $0 : -$0 }
}
```
let arr = arr.sorted { // invalid redeclaration of 'arr'
if first.filter { $0 == "1" }.count == second.filter { $0 == "1" }.count { // trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning
if first.filter { $0 == "1" }.count == second.filter { $0 == "1" }.count { // trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.sorted {
let a = String($0, radix: 2).filter { $0 == "1" }
let b = String($1, radix: 2).filter { $0 == "1" }
return a.count < b.count || a.count == b.count && $0 < $1
}
return arr.map { $0 >= 0 ? $0 : -$0 }
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 >= 0 ? $0 : -$0 }
let arr = arr.sorted {
let a = String($0, radix: 2).filter { $0 == "1" }
let b = String($1, radix: 2).filter { $0 == "1" }
return a.count < b.count || a.count == b.count && $0 < $1
}
return arr.map { $0 >= 0 ? $0 : -$0 }
}
```
let arr = arr.sorted { // invalid redeclaration of 'arr'
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 > 0 ? $0 : $0 * -1 }
let arr = arr.sorted {
let first = String($0, radix: 2)
let second = String($1, radix: 2)
let firstCount = first.filter { $0 == "1" }.count
let secondCount = second.filter { $0 == "1" }.count
if firstCount == secondCount {
return $0 < $1
}
return firstCount < secondCount
}
return arr.map { $0 > 0 ? $0 : $0 * -1 }
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { $0 > 0 ? $0 : $0 * -1 }
let arr = arr.sorted {
let first = String($0, radix: 2)
let second = String($1, radix: 2)
let firstCount = first.filter { $0 == "1" }.count
let secondCount = second.filter { $0 == "1" }.count
if firstCount == secondCount {
return $0 < $1
}
return firstCount < secondCount
}
return arr.map { $0 > 0 ? $0 : $0 * -1 }
}
```
let arr = arr.sorted { // invalid redeclaration of 'arr'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String($0, radix: 2).filter { $0 == "1" }
let b = String($1, radix: 2).filter { $0 == "1" }
return a.count < b.count || (a.count == b.count && $0 < $1)
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted {
let a = String($0, radix: 2).filter { $0 == "1" }
let b = String($1, radix: 2).filter { $0 == "1" }
return a.count < b.count || (a.count == b.count && $0 < $1)
}
}
```
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort {
let count1 = $0.nonzeroBitCount
let count2 = $1.nonzeroBitCount
if count1 == count2 {
return $0 < $1
}
return count1 < count2
}
return arr
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var arr = arr
arr.sort {
let count1 = $0.nonzeroBitCount
let count2 = $1.nonzeroBitCount
if count1 == count2 {
return $0 < $1
}
return count1 < count2
}
return arr
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = String(a, radix: 2)
let bBinary = String(b, radix: 2)
let aOnes = aBinary.filter { $0 == "1" }.count
let bOnes = bBinary.filter { $0 == "1" }.count
if aOnes == bOnes {
return a < b
} else {
return aOnes < bOnes
}
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = String(a, radix: 2)
let bBinary = String(b, radix: 2)
let aOnes = aBinary.filter { $0 == "1" }.count
let bOnes = bBinary.filter { $0 == "1" }.count
if aOnes == bOnes {
return a < b
} else {
return aOnes < bOnes
}
}
}
```
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { String($0, radix: 2) }
let arr = arr.map { $0.replacingOccurrences(of: "0", with: "") }
let arr = arr.map { $0.replacingOccurrences(of: "1", with: "") }
let arr = arr.map { $0.count }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map
XCTAssertTrue(sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 4, 3, 5]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [-2, -3, -4, -5, -6]) == [-4, -2, -6, -5, -3]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 4, 3]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [] as [Int]) == [] as [Int]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4]) == [2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [3, 6, 44, 12, 32, 5]) == [32, 3, 5, 6, 12, 44]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [2, 4, 8, 16, 32]) == [2, 4, 8, 16, 32]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [2, 4, 8, 16, 32]) == [2, 4, 8, 16, 32]) // cannot find 'sortArray' in scope
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let arr = arr.map { String($0, radix: 2) }
let arr = arr.map { $0.replacingOccurrences(of: "0", with: "") }
let arr = arr.map { $0.replacingOccurrences(of: "1", with: "") }
let arr = arr.map { $0.count }
let arr = arr.map { $0.sorted() }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map { $0.map { String($0) } }
let arr = arr.map { $0.map { Int($0)! } }
let arr = arr.map
XCTAssertTrue(sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 4, 3, 5]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [-2, -3, -4, -5, -6]) == [-4, -2, -6, -5, -3]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 4, 3]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [] as [Int]) == [] as [Int]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4]) == [2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [3, 6, 44, 12, 32, 5]) == [32, 3, 5, 6, 12, 44]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [2, 4, 8, 16, 32]) == [2, 4, 8, 16, 32]) // cannot find 'sortArray' in scope
XCTAssertTrue(sortArray(arr: [2, 4, 8, 16, 32]) == [2, 4, 8, 16, 32]) // cannot find 'sortArray' in scope
func selectWords(s: String, n: Int) -> [String] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char.isLetter && !char.isVowel {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char.isLetter && !char.isVowel {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
if char.isLetter && !char.isVowel { // value of type 'Character' has no member 'isVowel'
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if 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 words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != " " {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char.isLetter && !char.isVowel {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
extension Character {
var isVowel: Bool {
switch self.lowercased() {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char.isLetter && !char.isVowel {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
extension Character {
var isVowel: Bool {
switch self.lowercased() {
case "a", "e", "i", "o", "u":
return true
default:
return false
}
}
}
```
func selectWords(s: String, n: Int) -> [String] {
var result = [String]()
var words = s.components(separatedBy: " ")
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var result = [String]()
var words = s.components(separatedBy: " ")
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for letter in word {
if letter != "a" && letter != "e" && letter != "i" && letter != "o" && letter != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for letter in word {
if letter != "a" && letter != "e" && letter != "i" && letter != "o" && letter != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != " " {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 0
} else {
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 words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char != " " {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 0
} else {
count += 1
}
}
}
if count == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var count = 0
for char in word {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
```
var words = s.components(separatedBy: " ") // variable 'words' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.components(separatedBy: " ")
var result = [String]()
for word in words {
var consonants = 0
for char in word {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var closestVowel = ""
var closestVowelIndex = word.count
for (index, letter) in word.enumerated() {
if vowels.contains(String(letter)) {
let vowelIndex = word.index(word.startIndex, offsetBy: index)
let nextVowelIndex = word.index(word.startIndex, offsetBy: index + 1)
if word[nextVowelIndex].isLetter {
let nextVowel = String(word[nextVowelIndex])
if vowels.contains(nextVowel) {
closestVowel = nextVowel
closestVowelIndex = index + 1
}
}
}
}
if closestVowelIndex == word.count {
return ""
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var closestVowel = ""
var closestVowelIndex = word.count
for (index, letter) in word.enumerated() {
if vowels.contains(String(letter)) {
let vowelIndex = word.index(word.startIndex, offsetBy: index)
let nextVowelIndex = word.index(word.startIndex, offsetBy: index + 1)
if word[nextVowelIndex].isLetter {
let nextVowel = String(word[nextVowelIndex])
if vowels.contains(nextVowel) {
closestVowel = nextVowel
closestVowelIndex = index + 1
}
}
}
}
if closestVowelIndex == word.count {
return ""
}
return closestVowel
}
```
let vowelIndex = word.index(word.startIndex, offsetBy: index) // initialization of immutable value 'vowelIndex' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var charArray = Array(word)
for i in 0..<charArray.count {
if vowels.contains(charArray[i]) {
if consonants.contains(charArray[i-1]) && consonants.contains(charArray[i+1]) {
return String(charArray[i])
}
}
}
return ""
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var charArray = Array(word)
for i in 0..<charArray.count {
if vowels.contains(charArray[i]) {
if consonants.contains(charArray[i-1]) && consonants.contains(charArray[i+1]) {
return String(charArray[i])
}
}
}
return ""
}
```
var charArray = Array(word) // variable 'charArray' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var closestVowel = ""
for (index, char) in word.enumerated() {
if consonants.contains(char) {
for (index2, char2) in word.enumerated() {
if vowels.contains(char2) && index2 > index {
closestVowel = String(char2)
}
}
}
}
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 = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var closestVowel = ""
for (index, char) in word.enumerated() {
if consonants.contains(char) {
for (index2, char2) in word.enumerated() {
if vowels.contains(char2) && index2 > index {
closestVowel = String(char2)
}
}
}
}
return closestVowel
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
var vowels = "aeiouAEIOU"
var consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var vowelsArray = [Character]()
var consonantsArray = [Character]()
var closestVowel = ""
for char in word {
if vowels.contains(char) {
vowelsArray.append(char)
} else if consonants.contains(char) {
consonantsArray.append(char)
}
}
for (index, char) in consonantsArray.enumerated() {
if index < consonantsArray.count - 1 {
if consonantsArray[index + 1] == vowelsArray[0] {
closestVowel = String(vowelsArray[0])
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowels = "aeiouAEIOU"
var consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var vowelsArray = [Character]()
var consonantsArray = [Character]()
var closestVowel = ""
for char in word {
if vowels.contains(char) {
vowelsArray.append(char)
} else if consonants.contains(char) {
consonantsArray.append(char)
}
}
for (index, char) in consonantsArray.enumerated() {
if index < consonantsArray.count - 1 {
if consonantsArray[index + 1] == vowelsArray[0] {
closestVowel = String(vowelsArray[0])
}
}
}
return closestVowel
}
```
var vowels = "aeiouAEIOU" // variable 'vowels' was never mutated; consider changing to 'let' constant
var consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" // variable 'consonants' was never mutated; consider changing to 'let' constant
for (index, char) in consonantsArray.enumerated() { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
let wordArray = Array(word)
var vowelIndex = 0
var consonantIndex = 0
var closestVowel = ""
for (index, letter) in wordArray.enumerated() {
if consonants.contains(letter) {
consonantIndex = index
}
if vowels.contains(letter) {
vowelIndex = index
}
}
for (index, letter) in wordArray.enumerated() {
if vowels.contains(letter) {
if index > consonantIndex && index < vowelIndex {
closestVowel = String(letter)
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
let wordArray = Array(word)
var vowelIndex = 0
var consonantIndex = 0
var closestVowel = ""
for (index, letter) in wordArray.enumerated() {
if consonants.contains(letter) {
consonantIndex = index
}
if vowels.contains(letter) {
vowelIndex = index
}
}
for (index, letter) in wordArray.enumerated() {
if vowels.contains(letter) {
if index > consonantIndex && index < vowelIndex {
closestVowel = String(letter)
}
}
}
return closestVowel
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
var vowelsArray = [String]()
var consonantsArray = [String]()
for (index, char) in word.enumerated() {
if vowels.contains(char) {
vowelsArray.append(String(char))
}
if consonants.contains(char) {
consonantsArray.append(String(char))
}
}
if vowelsArray.count == 0 || consonantsArray.count == 0 {
return ""
}
let lastVowel = vowelsArray.last!
let lastConsonant = consonantsArray.last!
let lastVowelIndex = word.index(word.endIndex, offsetBy: -1)
let lastConsonantIndex = word.index(word.endIndex, offsetBy: -1)
let distance = word.distance(from: lastVowelIndex, to: lastConsonantIndex)
if distance == 1 {
return lastVowel
} else {
return ""
}
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let consonants = "bcdfghjklmnpqrstvwxyz"
var vowelsArray = [String]()
var consonantsArray = [String]()
for (index, char) in word.enumerated() {
if vowels.contains(char) {
vowelsArray.append(String(char))
}
if consonants.contains(char) {
consonantsArray.append(String(char))
}
}
if vowelsArray.count == 0 || consonantsArray.count == 0 {
return ""
}
let lastVowel = vowelsArray.last!
let lastConsonant = consonantsArray.last!
let lastVowelIndex = word.index(word.endIndex, offsetBy: -1)
let lastConsonantIndex = word.index(word.endIndex, offsetBy: -1)
let distance = word.distance(from: lastVowelIndex, to: lastConsonantIndex)
if distance == 1 {
return lastVowel
} else {
return ""
}
}
```
for (index, char) in word.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
let lastConsonant = consonantsArray.last! // initialization of immutable value 'lastConsonant' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
for i in (0..<word.count).reversed() {
let char = word[word.index(word.startIndex, offsetBy: i)]
if consonants.contains(char) {
for j in (0..<word.count).reversed() {
let char2 = word[word.index(word.startIndex, offsetBy: j)]
if vowels.contains(char2) {
return String(char2)
}
}
}
}
return ""
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
for i in (0..<word.count).reversed() {
let char = word[word.index(word.startIndex, offsetBy: i)]
if consonants.contains(char) {
for j in (0..<word.count).reversed() {
let char2 = word[word.index(word.startIndex, offsetBy: j)]
if vowels.contains(char2) {
return String(char2)
}
}
}
}
return ""
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var closestVowel = ""
var closestVowelIndex = 0
var isVowel = false
var isConsonant = false
var isVowelFound = false
var isConsonantFound = false
var isVowelFoundFirst = false
var isConsonantFoundFirst = false
for (index, char) in word.enumerated() {
if vowels.contains(char) {
isVowel = true
isVowelFound = true
isVowelFoundFirst = true
if isConsonantFoundFirst {
closestVowel = String(char)
closestVowelIndex = index
}
}
if consonants.contains(char) {
isConsonant = true
isConsonantFound = true
isConsonantFoundFirst = true
if isVowelFoundFirst {
closestVowel = String(char)
closestVowelIndex = index
}
}
if isVowel && isConsonant {
if index > closestVowelIndex {
closestVowel = String(char)
closestVowelIndex = index
}
}
if isVowel && !isConsonant {
isVowel = false
}
if !isVowel && isConsonant {
isConsonant = false
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiouAEIOU"
let consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
var closestVowel = ""
var closestVowelIndex = 0
var isVowel = false
var isConsonant = false
var isVowelFound = false
var isConsonantFound = false
var isVowelFoundFirst = false
var isConsonantFoundFirst = false
for (index, char) in word.enumerated() {
if vowels.contains(char) {
isVowel = true
isVowelFound = true
isVowelFoundFirst = true
if isConsonantFoundFirst {
closestVowel = String(char)
closestVowelIndex = index
}
}
if consonants.contains(char) {
isConsonant = true
isConsonantFound = true
isConsonantFoundFirst = true
if isVowelFoundFirst {
closestVowel = String(char)
closestVowelIndex = index
}
}
if isVowel && isConsonant {
if index > closestVowelIndex {
closestVowel = String(char)
closestVowelIndex = index
}
}
if isVowel && !isConsonant {
isVowel = false
}
if !isVowel && isConsonant {
isConsonant = false
}
}
return closestVowel
}
```
var isVowelFound = false // variable 'isVowelFound' was written to, but never read
var isConsonantFound = false // variable 'isConsonantFound' was written to, but never read
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var closestVowel = ""
var closestVowelIndex = 0
var wordArray = Array(word)
for (index, char) in wordArray.reversed().enumerated() {
if consonants.contains(String(char)) {
if vowels.contains(String(wordArray[index + 1])) {
closestVowel = String(wordArray[index + 1])
closestVowelIndex = index + 1
}
}
}
if closestVowelIndex == 0 {
return ""
} else {
return closestVowel
}
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var closestVowel = ""
var closestVowelIndex = 0
var wordArray = Array(word)
for (index, char) in wordArray.reversed().enumerated() {
if consonants.contains(String(char)) {
if vowels.contains(String(wordArray[index + 1])) {
closestVowel = String(wordArray[index + 1])
closestVowelIndex = index + 1
}
}
}
if closestVowelIndex == 0 {
return ""
} else {
return closestVowel
}
}
```
var wordArray = Array(word) // variable 'wordArray' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var vowel = ""
var isVowel = false
for i in word.indices {
let char = String(word[i])
if consonants.contains(char) {
if isVowel {
vowel = char
isVowel = false
}
} else if vowels.contains(char) {
isVowel = true
}
}
return vowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var vowel = ""
var isVowel = false
for i in word.indices {
let char = String(word[i])
if consonants.contains(char) {
if isVowel {
vowel = char
isVowel = false
}
} else if vowels.contains(char) {
isVowel = true
}
}
return vowel
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
let str1 = lst[0]
let str2 = lst[1]
var str = ""
for i in 0..<str1.count {
str += String(str1[str1.index(str1.startIndex, offsetBy: i)])
}
for i in 0..<str2.count {
str += String(str2[str2.index(str2.startIndex, offsetBy: i)])
}
var count = 0
for i in 0..<str.count {
if str[str.index(str.startIndex, offsetBy: i)] == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
let str1 = lst[0]
let str2 = lst[1]
var str = ""
for i in 0..<str1.count {
str += String(str1[str1.index(str1.startIndex, offsetBy: i)])
}
for i in 0..<str2.count {
str += String(str2[str2.index(str2.startIndex, offsetBy: i)])
}
var count = 0
for i in 0..<str.count {
if str[str.index(str.startIndex, offsetBy: i)] == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for str in lst {
for char in str {
if char == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
}
if count == 0 {
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 count = 0
for str in lst {
for char in str {
if char == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
}
if count == 0 {
return "Yes"
}
return "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
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 {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var count = 0
for i in lst {
if i == "(" {
count += 1
} else {
count -= 1
}
if count < 0 {
return "No"
}
}
if count == 0 {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var arr = arr
arr.sort()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var arr = arr
arr.sort()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var result = [Int]()
for _ in 0..<k {
let max = arr.max()
if let max = max {
result.append(max)
arr.remove(at: arr.firstIndex(of: max)!)
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var result = [Int]()
for _ in 0..<k {
let max = arr.max()
if let max = max {
result.append(max)
arr.remove(at: arr.firstIndex(of: max)!)
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
arr.sort()
var result = [Int]()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
arr.sort()
var result = [Int]()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var result = [Int]()
for _ in 0..<k {
var max = arr[0]
var maxIndex = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
result.append(max)
arr.remove(at: maxIndex)
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var result = [Int]()
for _ in 0..<k {
var max = arr[0]
var maxIndex = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
result.append(max)
arr.remove(at: maxIndex)
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var arr = arr
for _ in 0..<k {
var max = arr[0]
var maxIndex = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
result.append(max)
arr.remove(at: maxIndex)
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var arr = arr
for _ in 0..<k {
var max = arr[0]
var maxIndex = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
maxIndex = i
}
}
result.append(max)
arr.remove(at: maxIndex)
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var result = [Int]()
for _ in 0..<k {
let max = arr.max()
if let max = max {
result.append(max)
arr.remove(at: arr.firstIndex(of: max)!)
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
var result = [Int]()
for _ in 0..<k {
let max = arr.max()
if let max = max {
result.append(max)
arr.remove(at: arr.firstIndex(of: max)!)
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var arr = arr
for _ in 0..<k {
var max = Int.min
var index = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
index = i
}
}
result.append(max)
arr.remove(at: index)
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var arr = arr
for _ in 0..<k {
var max = Int.min
var index = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
index = i
}
}
result.append(max)
arr.remove(at: index)
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
arr.sort()
var result = [Int]()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
arr.sort()
var result = [Int]()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var count = 0
var max = Int.min
var min = Int.max
for i in arr {
if i > max {
max = i
}
if i < min {
min = i
}
}
for i in arr {
if i == max || i == min {
result.append(i)
count += 1
}
if count == k {
break
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var count = 0
var max = Int.min
var min = Int.max
for i in arr {
if i > max {
max = i
}
if i < min {
min = i
}
}
for i in arr {
if i == max || i == min {
result.append(i)
count += 1
}
if count == k {
break
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
arr.sort()
var result = [Int]()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var arr = arr
arr.sort()
var result = [Int]()
for i in 0..<k {
result.append(arr[arr.count - 1 - i])
}
return result
}
```
// XCTAssertTrue failed
func solution(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, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
sum += value
}
}
return sum
}
```
func solution(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, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
sum += value
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() where index % 2 == 0 && value % 2 != 0 {
sum += value
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() where index % 2 == 0 && value % 2 != 0 {
sum += value
}
return sum
}
```
func solution(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, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
sum += value
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 }.reduce(0, +)
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 }.reduce(0, +)
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var result = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
result += value
}
}
return result
}
```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 result = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
result += value
}
}
return result
}
```
func solution(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, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
sum += value
}
}
return sum
}
```
func solution(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, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for (index, value) in lst.enumerated() {
if index % 2 == 0 && value % 2 != 0 {
sum += value
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 }.reduce(0, +)
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
return lst.filter { $0 % 2 == 0 }.reduce(0, +)
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
let num = arr[i]
if num < 100 {
sum += num
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current > 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current > 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
if current % 2 == 1 {
result.append(current)
}
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
if current % 2 == 1 {
result.append(current)
}
}
return result
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
if current % 2 == 1 {
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 = current * 3 + 1
}
if current % 2 == 1 {
result.append(current)
}
}
result.append(1)
return result
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
if current % 2 != 0 {
result.append(current)
}
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
if current % 2 != 0 {
result.append(current)
}
}
return result
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2 != 0 {
arr.append(num)
}
}
return arr
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = num * 3 + 1
}
if num % 2 != 0 {
arr.append(num)
}
}
return arr
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var i = n
while i != 1 {
if i % 2 == 0 {
i = i / 2
} else {
i = i * 3 + 1
}
if i % 2 != 0 {
arr.append(i)
}
}
return arr
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var i = n
while i != 1 {
if i % 2 == 0 {
i = i / 2
} else {
i = i * 3 + 1
}
if i % 2 != 0 {
arr.append(i)
}
}
return arr
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [1]
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
result.append(current)
}
return result.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [1]
var current = n
while current != 1 {
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
result.append(current)
}
return result.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
collatz = collatz.filter { $0 % 2 != 0 }
return collatz.sorted()
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current != 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
collatz = collatz.filter { $0 % 2 != 0 }
return collatz.sorted()
}
```
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current > 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var current = n
while current > 1 {
collatz.append(current)
if current % 2 == 0 {
current = current / 2
} else {
current = current * 3 + 1
}
}
collatz.append(1)
return collatz.filter { $0 % 2 != 0 }
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let date = date.components(separatedBy: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if date.count != 3 {
return false
}
if month == nil || day == nil || year == nil {
return false
}
if day! < 1 || day! > 31 || month! < 1 || month! > 12 || year! < 1 {
return false
}
if month! == 2 && day! > 29 {
return false
}
if month! == 4 || month! == 6 || month! == 9 || month! == 11 {
if day! > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.components(separatedBy: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if date.count != 3 {
return false
}
if month == nil || day == nil || year == nil {
return false
}
if day! < 1 || day! > 31 || month! < 1 || month! > 12 || year! < 1 {
return false
}
if month! == 2 && day! > 29 {
return false
}
if month! == 4 || month! == 6 || month! == 9 || month! == 11 {
if day! > 30 {
return false
}
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let dateArray = date.components(separatedBy: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0]) ?? 0
let day = Int(dateArray[1]) ?? 0
let year = Int(dateArray[2]) ?? 0
if month < 1 || month > 12 {
return false
}
if day < 1 || day > 31 {
return false
}
if year < 1 {
return false
}
if month == 2 && day > 29 {
return false
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.components(separatedBy: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0]) ?? 0
let day = Int(dateArray[1]) ?? 0
let year = Int(dateArray[2]) ?? 0
if month < 1 || month > 12 {
return false
}
if day < 1 || day > 31 {
return false
}
if year < 1 {
return false
}
if month == 2 && day > 29 {
return false
}
if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1900 || year! > 2099 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1900 || year! > 2099 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1 || year! > 2020 {
return false
}
return true
}
```
// Fatal error: Index out of range
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1900 || year! > 2100 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let date = date.split(separator: "-")
let month = Int(date[0])
let day = Int(date[1])
let year = Int(date[2])
if month == nil || day == nil || year == nil {
return false
}
if month! < 1 || month! > 12 {
return false
}
if day! < 1 || day! > 31 {
return false
}
if year! < 1900 || year! > 2100 {
return false
}
return true
}
```
// Fatal error: Index out of range
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let letters = txt.components(separatedBy: ",")
if letters.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(letters)
}
} else {
return .success(words)
}
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let letters = txt.components(separatedBy: ",")
if letters.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(letters)
}
} else {
return .success(words)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let letters = txt.components(separatedBy: ",")
if letters.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(letters)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let letters = txt.components(separatedBy: ",")
if letters.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(letters)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let letters = txt.components(separatedBy: ",")
if letters.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(letters)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let letters = txt.components(separatedBy: ",")
if letters.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(letters)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords
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> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let lowerCaseLetters = txt.filter { $0.isLowercase }
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
} else {
return .success(words)
}
}
func mostVowels(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxVowels = 0
var maxVowelWord = ""
for word in words {
var vowelsCount = 0
for char in word {
if vowels.contains(String(char)) {
vowelsCount += 1
}
}
if vowelsCount > maxVowels {
maxVowels = vowelsCount
maxVowelWord = word
}
}
return maxVowelWord
}
func mostConsonants(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxConsonants = 0
var maxConsonantWord = ""
for word in words {
var consonantsCount = 0
for char in word {
if !vowels.contains(String(char)) {
consonantsCount += 1
}
}
if consonantsCount > maxConsonants {
maxConsonants = consonantsCount
maxConsonantWord = word
}
}
return maxConsonantWord
}
func mostVowelsAndConsonants(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxVowels = 0
var maxConsonants = 0
var maxVowelWord = ""
var maxConsonantWord = ""
for word in words {
var vowelsCount = 0
var consonantsCount = 0
for char in word {
if vowels.contains(String(char)) {
vowelsCount += 1
} else {
consonantsCount += 1
}
}
if vowelsCount > maxVowels {
maxVowels = vowelsCount
maxVowelWord = word
}
if consonantsCount > maxConsonants {
maxConsonants = consonantsCount
maxConsonantWord = word
}
}
return maxVowelWord + maxConsonantWord
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let lowerCaseLetters = txt.filter { $0.isLowercase }
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
} else {
return .success(words)
}
}
// Given a list of words, return the word with the most vowels
// Examples
// mostVowels(words: ["apple", "banana", "orange"]) == "banana"
// mostVowels(words: ["apple", "banana", "orange", "pear"]) == "banana"
func mostVowels(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxVowels = 0
var maxVowelWord = ""
for word in words {
var vowelsCount = 0
for char in word {
if vowels.contains(String(char)) {
vowelsCount += 1
}
}
if vowelsCount > maxVowels {
maxVowels = vowelsCount
maxVowelWord = word
}
}
return maxVowelWord
}
// Given a list of words, return the word with the most consonants
// Examples
// mostConsonants(words: ["apple", "banana", "orange"]) == "apple"
// mostConsonants(words: ["apple", "banana", "orange", "pear"]) == "apple"
func mostConsonants(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxConsonants = 0
var maxConsonantWord = ""
for word in words {
var consonantsCount = 0
for char in word {
if !vowels.contains(String(char)) {
consonantsCount += 1
}
}
if consonantsCount > maxConsonants {
maxConsonants = consonantsCount
maxConsonantWord = word
}
}
return maxConsonantWord
}
// Given a list of words, return the word with the most vowels and consonants
// Examples
// mostVowelsAndConsonants(words: ["apple", "banana", "orange"]) == "banana"
// mostVowelsAndConsonants(words: ["apple", "banana", "orange", "pear"]) == "banana"
func mostVowelsAndConsonants(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxVowels = 0
var maxConsonants = 0
var maxVowelWord = ""
var maxConsonantWord = ""
for word in words {
var vowelsCount = 0
var consonantsCount = 0
for char in word {
if vowels.contains(String(char)) {
vowelsCount += 1
} else {
consonantsCount += 1
}
}
if vowelsCount > maxVowels {
maxVowels = vowelsCount
maxVowelWord = word
}
if consonantsCount > maxConsonants {
maxConsonants = consonantsCount
maxConsonantWord = word
}
}
return maxVowelWord + maxConsonantWord
}
// Given a list of words, return the word with the most vowels and consonants
// Examples
// mostVowelsAndConsonants(words: ["apple", "banana", "orange"]) == "banana"
// mostVowelsAndConsonants(words: ["apple", "banana", "orange", "pear"]) == "banana"
func mostVowelsAndConsonants(words: [String]) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var maxVowels = 0
var maxConsonants = 0
var maxVowelWord = ""
var maxConsonantWord = ""
for word in words {
var vowelsCount = 0
var consonantsCount = 0
for char in word {
if vowels.contains(String(char)) {
vowelsCount += 1
} else {
consonantsCount += 1
}
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let lowerCaseLetters = txt.lowercased()
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
}
}
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let lowerCaseLetters = txt.lowercased()
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let lowerCaseLetters = txt.lowercased()
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let lowerCaseLetters = txt.lowercased()
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let lowerCaseLetters = txt.lowercased()
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let lowerCaseLetters = txt.lowercased()
let oddOrderLetters = lowerCaseLetters.filter { $0.asciiValue! % 2 == 1 }
return .failure(oddOrderLetters.count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a')
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> {
let words = txt.split(separator: " ")
if words.count > 0 {
return .success(words.map { String($0) })
}
let commas = txt.split(separator: ",")
if commas.count > 0 {
return .success(commas.map { String($0) })
}
let letters = txt.filter { $0.isLowercase }
let count = letters.reduce(0) { $0 + ($1.asciiValue! - 97) % 2 }
return .failure(count)
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count > 0 {
return .success(words.map { String($0) })
}
let commas = txt.split(separator: ",")
if commas.count > 0 {
return .success(commas.map { String($0) })
}
let letters = txt.filter { $0.isLowercase }
let count = letters.reduce(0) { $0 + ($1.asciiValue! - 97) % 2 }
return .failure(count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count > 0 {
return .success(words.map { String($0) })
}
let commas = txt.split(separator: ",")
if commas.count > 0 {
return .success(commas.map { String($0) })
}
let letters = txt.filter { $0.isLowercase }
let count = letters.reduce(0) { $0 + ($1.asciiValue! - 97) % 2 }
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count > 0 {
return .success(words.map { String($0) })
}
let commas = txt.split(separator: ",")
if commas.count > 0 {
return .success(commas.map { String($0) })
}
let letters = txt.filter { $0.isLowercase }
let count = letters.reduce(0) { $0 + ($1.asciiValue! - 97) % 2 }
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count > 0 {
return .success(words.map { String($0) })
}
let commas = txt.split(separator: ",")
if commas.count > 0 {
return .success(commas.map { String($0) })
}
let letters = txt.filter { $0.isLowercase }
let count = letters.reduce(0) { $0 + ($1.asciiValue! - 97) % 2 }
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count > 0 {
return .success(words.map { String($0) })
}
let commas = txt.split(separator: ",")
if commas.count > 0 {
return .success(commas.map { String($0) })
}
let letters = txt.filter { $0.isLowercase }
let count = letters.reduce(0) { $0 + ($1.asciiValue! - 97) %
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return .failure(count) // cannot convert value of type 'UInt8' to expected argument type 'Int'
func splitWords(txt: String) -> Result<[String], Int> { // invalid redeclaration of 'splitWords(txt:)'
return .failure(count) // cannot convert value of type 'UInt8' to expected argument type 'Int'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let count = txt.reduce(0) { partialResult, char in
let char = char.lowercased()
if char.isLetter && char.unicodeScalars.first!.value % 2 == 1 {
return partialResult + 1
}
return partialResult
}
return .failure(count)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(separator: " ").map { String($0) })
} else if txt.contains(",") {
return .success(txt.split(separator: ",").map { String($0) })
} else {
let count = txt.reduce(0) { partialResult, char in
let char = char.lowercased()
if char.isLetter && char.unicodeScalars.first!.value % 2 == 1 {
return partialResult + 1
}
return partialResult
}
return .failure(count)
}
}
print(splitWords(txt: "Hello world!"))
print(splitWords(txt: "Hello,world!"))
print(splitWords(txt: "abcdef"))
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let count = txt.reduce(0) { partialResult, char in // missing argument label 'into:' in call
let count = txt.reduce(0) { partialResult, char in // cannot convert value of type 'Int' to expected argument type '(inout @escaping (_, _) -> Int, String.Element) throws -> ()' (aka '(inout @escaping (_, _) -> Int, Character) throws -> ()')
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let chars = txt.components(separatedBy: ",")
if chars.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(chars)
}
} else {
return .success(words)
}
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let chars = txt.components(separatedBy: ",")
if chars.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(chars)
}
} else {
return .success(words)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let chars = txt.components(separatedBy: ",")
if chars.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(chars)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let chars = txt.components(separatedBy: ",")
if chars.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(chars)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let chars = txt.components(separatedBy: ",")
if chars.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(chars)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.isEmpty {
let chars = txt.components(separatedBy: ",")
if chars.isEmpty {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
} else {
return .success(chars)
}
} else {
return .success(words)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords
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> {
let words = txt.components(separatedBy: " ")
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
var count = 0
for char in txt {
if char.isLowercase {
let index = char.asciiValue! - 97
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
var count = 0
for char in txt {
if char.isLowercase {
let index = char.asciiValue! - 97
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
var count = 0
for char in txt {
if char.isLowercase {
let index = char.asciiValue! - 97
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
var count = 0
for char in txt {
if char.isLowercase {
let index = char.asciiValue! - 97
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
var count = 0
for char in txt {
if char.isLowercase {
let index = char.asciiValue! - 97
if index % 2 == 1 {
count += 1
}
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.components(separatedBy: " ")
if words.count > 1 {
return .success(words)
}
let words2 = txt.components(separatedBy: ",")
if words2.count > 1 {
return .success(words2)
}
var count = 0
for char in txt {
if char.isLowercase {
let index = char.asciiValue!
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> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
let words3 = txt.split(separator: "")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
func splitWords2(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
func splitWords3(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
func splitWords4(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
let words3 = txt.split(separator: "")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords2(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords3(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords4(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
if words.count > 0 {
return .success(words.map { String($0) })
} else if words2.count > 0 {
return .success(words2.map { String($0) })
} else {
let count = txt.filter { $0.isLowercase && $0.asciiValue! % 2 == 1 }.count
return .failure(count)
}
}
// Given a
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let words3 = txt.split(separator: "") // initialization of immutable value 'words3' was never used; consider replacing with assignment to '_' or removing it
extension Int: Error {
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
let words3 = txt.split(separator: "a")
let words4 = txt.split(separator: "b")
let words5 = txt.split(separator: "c")
let words6 = txt.split(separator: "d")
let words7 = txt.split(separator: "e")
let words8 = txt.split(separator: "f")
let words9 = txt.split(separator: "g")
let words10 = txt.split(separator: "h")
let words11 = txt.split(separator: "i")
let words12 = txt.split(separator: "j")
let words13 = txt.split(separator: "k")
let words14 = txt.split(separator: "l")
let words15 = txt.split(separator: "m")
let words16 = txt.split(separator: "n")
let words17 = txt.split(separator: "o")
let words18 = txt.split(separator: "p")
let words19 = txt.split(separator: "q")
let words20 = txt.split(separator: "r")
let words21 = txt.split(separator: "s")
let words22 = txt.split(separator: "t")
let words23 = txt.split(separator: "u")
let words24 = txt.split(separator: "v")
let words25 = txt.split(separator: "w")
let words26 = txt.split(separator: "x")
let words27 = txt.split(separator: "y")
let words28 = txt.split(separator: "z")
if words.count > 0 {
return .success(words)
} else if words2.count > 0 {
return .success(words2)
} else if words3.count > 0 {
return .success(words3)
} else if words4.count > 0 {
return .success(words4)
} else if words5.count > 0 {
return .success(words5)
} else if words6.count > 0 {
return .success(words6)
} else if words7.count > 0 {
return .success(words7)
} else if words8.count > 0 {
return .success(words8)
} else if words9.count > 0 {
return .success(words9)
} else if words10.count > 0 {
return .success(words10)
} else if words11.count > 0 {
return .success(words11)
} else if words12.count > 0 {
return .success(words12)
} else if words13.count > 0 {
return .success(words13)
} else if words14.count > 0 {
return .success(words14)
} else if words15.count > 0 {
return .success(words15)
} else if words16.count > 0 {
return .success(words16)
} else if words17.count > 0 {
return .success(words17)
} else if words18.count > 0 {
return .success(words18)
} else if words19.count > 0 {
return .success(words19)
} else if words20.count > 0 {
return .success(words20)
} else if words21.count > 0 {
return .success(words21)
} else if words22.count > 0 {
return .success(words22)
} else if words23.count > 0 {
return .success(words23)
} else if words24.count > 0 {
return .success(words24)
} else if words25.count > 0 {
return .success(words25)
} else if words26
XCTAssertTrue(splitWords(txt: "Hello world!") == .success(["Hello", "world!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "Hello world,!") == .success(["Hello", "world,!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "Hello,Hello,world !") == .success(["Hello,Hello,world", "!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "abcdef") == .failure(3)) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "aaabb") == .failure(2)) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "aaaBb") == .failure(1)) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "") == .failure(0)) // cannot find 'splitWords' in scope
extension Int: Error {
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
let words2 = txt.split(separator: ",")
let words3 = txt.lowercased().filter { $0.isLetter }
let words4 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words5 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words6 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words7 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words8 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words9 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words10 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words11 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words12 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words13 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words14 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words15 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words16 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words17 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words18 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words19 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words20 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words21 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words22 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words23 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words24 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words25 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words26 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words27 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words28 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words29 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words30 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words31 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words32 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words33 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words34 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words35 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words36 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words37 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words38 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words39 = txt.lowercased().filter { $0.isLetter }.map { String($0) }
let words40 = txt.lowercased().
XCTAssertTrue(splitWords(txt: "Hello world!") == .success(["Hello", "world!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "Hello world,!") == .success(["Hello", "world,!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "Hello,Hello,world !") == .success(["Hello,Hello,world", "!"])) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "abcdef") == .failure(3)) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "aaabb") == .failure(2)) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "aaaBb") == .failure(1)) // cannot find 'splitWords' in scope
XCTAssertTrue(splitWords(txt: "") == .failure(0)) // cannot find 'splitWords' in scope
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var i = 0
while i < lst.count - 1 && sorted {
if lst[i] > lst[i + 1] {
sorted = false
}
i += 1
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var i = 0
while i < lst.count - 1 && sorted {
if lst[i] > lst[i + 1] {
sorted = false
}
i += 1
}
return sorted
}
```
// XCTAssertTrue failed
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 {
var sorted = true
for i in 0..<lst.count {
if i < lst.count - 1 && lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count {
if i < lst.count - 1 && lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var duplicates = false
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
if lst.filter({$0 == lst[i]}).count > 1 {
duplicates = true
}
}
return sorted && !duplicates
}
```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 duplicates = false
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
if lst.filter({$0 == lst[i]}).count > 1 {
duplicates = true
}
}
return sorted && !duplicates
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count-1 {
if lst[i] > lst[i+1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count-1 {
if lst[i] > lst[i+1] {
sorted = false
}
}
return sorted
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count {
if i == lst.count - 1 {
break
}
if lst[i] > lst[i + 1] {
sorted = false
break
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count {
if i == lst.count - 1 {
break
}
if lst[i] > lst[i + 1] {
sorted = false
break
}
}
return sorted
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count {
if i < lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count {
if i < lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
}
return sorted
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
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 {
var sorted = true
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
```
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length == 0 {
return "NO"
}
if length == 1 || length == 2 {
return "YES"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length == 0 {
return "NO"
}
if length == 1 || length == 2 {
return "YES"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start + 1
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return first * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return first * product
}
```
let sum = arr.reduce(0) { $0 + abs($1) } // initialization of immutable value 'sum' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product: Int = 1
var sum: Int = 0
for num in arr {
product *= num < 0 ? -1 : 1
sum += abs(num)
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product: Int = 1
var sum: Int = 0
for num in arr {
product *= num < 0 ? -1 : 1
sum += abs(num)
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return product * sum
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return product * sum
}
```
guard let first = arr.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return sum * product
}
```
guard let first = arr.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
product *= num > 0 ? 1 : -1
sum += abs(num)
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
product *= num > 0 ? 1 : -1
sum += abs(num)
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
sum += abs(num)
product *= (num == 0 ? 1 : num / abs(num))
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
sum += abs(num)
product *= (num == 0 ? 1 : num / abs(num))
}
return sum * product
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
product *= (num > 0 ? 1 : -1)
sum += abs(num)
}
return product * sum
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
product *= (num > 0 ? 1 : -1)
sum += abs(num)
}
return product * sum
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
if num == 0 {
sum = 0
break
}
product *= num < 0 ? -1 : 1
sum += abs(num)
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
if num == 0 {
sum = 0
break
}
product *= num < 0 ? -1 : 1
sum += abs(num)
}
return sum * product
}
```
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard let first = arr.first else { return nil }
let product = arr.reduce(1) { $0 * $1 }
let sum = arr.reduce(0) { $0 + abs($1) }
return sum * product
}
```
guard let first = arr.first else { return nil } // value 'first' was defined but never used; consider replacing with boolean test
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
if num == 0 {
sum += 0
} else {
sum += abs(num)
product *= num < 0 ? -1 : 1
}
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else { return nil }
var product = 1
var sum = 0
for num in arr {
if num == 0 {
sum += 0
} else {
sum += abs(num)
product *= num < 0 ? -1 : 1
}
}
return sum * product
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(repeating: Array(repeating: Array(repeating: 0, count: k + 1), count: m), count: n)
for i in 0..<n {
for j in 0..<m {
for l in 0...k {
d[i][j][l] = -1
}
}
}
func dfs(i: Int, j: Int, l: Int) -> Int {
if l == k {
return 0
}
if d[i][j][l] != -1 {
return d[i][j][l]
}
var res = Int.max
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
res = min(res, dfs(i: x, j: y, l: l + 1) + abs(grid[i][j] - grid[x][y]))
}
}
d[i][j][l] = res
return res
}
let res = dfs(i: 0, j: 0, l: 0)
var ans = [Int]()
var i = 0, j = 0, l = 0
while l < k {
var minVal = Int.max
var minI = -1, minJ = -1
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m && d[x][y][l + 1] + abs(grid[i][j] - grid[x][y]) == res {
if grid[x][y] < minVal {
minVal = grid[x][y]
minI = x
minJ = y
}
}
}
ans.append(minVal)
i = minI
j = minJ
l += 1
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(repeating: Array(repeating: Array(repeating: 0, count: k + 1), count: m), count: n)
for i in 0..<n {
for j in 0..<m {
for l in 0...k {
d[i][j][l] = -1
}
}
}
func dfs(i: Int, j: Int, l: Int) -> Int {
if l == k {
return 0
}
if d[i][j][l] != -1 {
return d[i][j][l]
}
var res = Int.max
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
res = min(res, dfs(i: x, j: y, l: l + 1) + abs(grid[i][j] - grid[x][y]))
}
}
d[i][j][l] = res
return res
}
let res = dfs(i: 0, j: 0, l: 0)
var ans = [Int]()
var i = 0, j = 0, l = 0
while l < k {
var minVal = Int.max
var minI = -1, minJ = -1
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m && d[x][y][l + 1] + abs(grid[i][j] - grid[x][y]) == res {
if grid[x][y] < minVal {
minVal = grid[x][y]
minI = x
minJ = y
}
}
}
ans.append(minVal)
i = minI
j = minJ
l += 1
}
return ans
}
```
d[i][j][l] = -1 // cannot assign through subscript: 'd' is a 'let' constant
d[i][j][l] = res // cannot assign through subscript: 'd' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(1...n * m)
let s = Array(1...k)
let dp = Array(repeating: Array(repeating: Array(repeating: 0, count: k + 1), count: n), count: m)
for i in 0..<n {
for j in 0..<m {
dp[i][j][0] = Int.max
}
}
for i in 0..<n {
for j in 0..<m {
dp[i][j][1] = grid[i][j]
}
}
for i in 0..<n {
for j in 0..<m {
for l in 2...k {
dp[i][j][l] = Int.max
for x in 0..<n {
for y in 0..<m {
if i == x && j == y {
continue
}
dp[i][j][l] = min(dp[i][j][l], dp[x][y][l - 1] + grid[i][j])
}
}
}
}
}
var res = [Int]()
var i = 0
var j = 0
var l = k
while l > 0 {
res.append(grid[i][j])
var minVal = Int.max
var minI = 0
var minJ = 0
for x in 0..<n {
for y in 0..<m {
if i == x && j == y {
continue
}
if dp[x][y][l - 1] + grid[i][j] < minVal {
minVal = dp[x][y][l - 1] + grid[i][j]
minI = x
minJ = y
}
}
}
i = minI
j = minJ
l -= 1
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(1...n * m)
let s = Array(1...k)
let dp = Array(repeating: Array(repeating: Array(repeating: 0, count: k + 1), count: n), count: m)
for i in 0..<n {
for j in 0..<m {
dp[i][j][0] = Int.max
}
}
for i in 0..<n {
for j in 0..<m {
dp[i][j][1] = grid[i][j]
}
}
for i in 0..<n {
for j in 0..<m {
for l in 2...k {
dp[i][j][l] = Int.max
for x in 0..<n {
for y in 0..<m {
if i == x && j == y {
continue
}
dp[i][j][l] = min(dp[i][j][l], dp[x][y][l - 1] + grid[i][j])
}
}
}
}
}
var res = [Int]()
var i = 0
var j = 0
var l = k
while l > 0 {
res.append(grid[i][j])
var minVal = Int.max
var minI = 0
var minJ = 0
for x in 0..<n {
for y in 0..<m {
if i == x && j == y {
continue
}
if dp[x][y][l - 1] + grid[i][j] < minVal {
minVal = dp[x][y][l - 1] + grid[i][j]
minI = x
minJ = y
}
}
}
i = minI
j = minJ
l -= 1
}
return res
}
```
dp[i][j][0] = Int.max // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j][1] = grid[i][j] // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j][l] = Int.max // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j][l] = min(dp[i][j][l], dp[x][y][l - 1] + grid[i][j]) // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for l in 1...k {
for i in 0..<n {
for j in 0..<m {
var min = Int.max
for x in 0..<n {
for y in 0..<m {
if i != x || j != y {
min = min(min, dp[l - 1][x][y])
}
}
}
dp[l][i][j] = min + grid[i][j]
}
}
}
var res = [Int]()
var i = 0
var j = 0
for l in stride(from: k, to: 0, by: -1) {
res.append(dp[l][i][j])
var min = Int.max
for x in 0..<n {
for y in 0..<m {
if i != x || j != y {
min = min(min, dp[l - 1][x][y])
}
}
}
i = x
j = y
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for l in 1...k {
for i in 0..<n {
for j in 0..<m {
var min = Int.max
for x in 0..<n {
for y in 0..<m {
if i != x || j != y {
min = min(min, dp[l - 1][x][y])
}
}
}
dp[l][i][j] = min + grid[i][j]
}
}
}
var res = [Int]()
var i = 0
var j = 0
for l in stride(from: k, to: 0, by: -1) {
res.append(dp[l][i][j])
var min = Int.max
for x in 0..<n {
for y in 0..<m {
if i != x || j != y {
min = min(min, dp[l - 1][x][y])
}
}
}
i = x
j = y
}
return res
}
```
min = min(min, dp[l - 1][x][y]) // cannot call value of non-function type 'Int'
min = min(min, dp[l - 1][x][y]) // cannot call value of non-function type 'Int'
i = x // cannot find 'x' in scope
j = y // cannot find 'y' in scope
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let inf = 1000000000
var dp = Array(repeating: Array(repeating: Array(repeating: inf, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1...k {
for j in 0..<n {
for l in 0..<m {
for (x, y) in [(j - 1, l), (j + 1, l), (j, l - 1), (j, l + 1)] {
if x < 0 || x >= n || y < 0 || y >= m {
continue
}
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][x][y])
}
}
}
}
var ans = [Int]()
var i = n - 1
var j = m - 1
for k in stride(from: k, to: 0, by: -1) {
ans.append(dp[k][i][j])
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x < 0 || x >= n || y < 0 || y >= m {
continue
}
if dp[k][i][j] == dp[k - 1][x][y] {
i = x
j = y
break
}
}
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let inf = 1000000000
var dp = Array(repeating: Array(repeating: Array(repeating: inf, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1...k {
for j in 0..<n {
for l in 0..<m {
for (x, y) in [(j - 1, l), (j + 1, l), (j, l - 1), (j, l + 1)] {
if x < 0 || x >= n || y < 0 || y >= m {
continue
}
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][x][y])
}
}
}
}
var ans = [Int]()
var i = n - 1
var j = m - 1
for k in stride(from: k, to: 0, by: -1) {
ans.append(dp[k][i][j])
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x < 0 || x >= n || y < 0 || y >= m {
continue
}
if dp[k][i][j] == dp[k - 1][x][y] {
i = x
j = y
break
}
}
}
return ans
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let k = k
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1...k {
for j in 0..<n {
for l in 0..<m {
dp[i][j][l] = Int.max
for (x, y) in [(j - 1, l), (j + 1, l), (j, l - 1), (j, l + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][x][y])
}
}
}
}
}
var res = [Int]()
var i = n - 1
var j = m - 1
for k in stride(from: k, to: 0, by: -1) {
res.append(dp[k][i][j])
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m && dp[k][i][j] == dp[k][x][y] {
i = x
j = y
break
}
}
}
return res.reversed()
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let k = k
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1...k {
for j in 0..<n {
for l in 0..<m {
dp[i][j][l] = Int.max
for (x, y) in [(j - 1, l), (j + 1, l), (j, l - 1), (j, l + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][x][y])
}
}
}
}
}
var res = [Int]()
var i = n - 1
var j = m - 1
for k in stride(from: k, to: 0, by: -1) {
res.append(dp[k][i][j])
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m && dp[k][i][j] == dp[k][x][y] {
i = x
j = y
break
}
}
}
return res.reversed()
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(repeating: Array(repeating: Array(repeating: 0, count: n * m + 1), count: n * m + 1), count: n * m + 1)
for i in 0..<n {
for j in 0..<m {
for k in 0..<n * m {
d[i][j][k] = -1
}
}
}
func dfs(i: Int, j: Int, k: Int) -> Int {
if k == 0 {
return 0
}
if d[i][j][k] != -1 {
return d[i][j][k]
}
var res = Int.max
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
res = min(res, dfs(i: x, j: y, k: k - 1) + abs(grid[i][j] - grid[x][y]))
}
}
d[i][j][k] = res
return res
}
let res = dfs(i: 0, j: 0, k: k)
var path = [Int]()
var i = 0, j = 0, k = k
while k > 0 {
var minVal = Int.max
var minI = -1, minJ = -1
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
if d[x][y][k - 1] + abs(grid[i][j] - grid[x][y]) < minVal {
minVal = d[x][y][k - 1] + abs(grid[i][j] - grid[x][y])
minI = x
minJ = y
}
}
}
path.append(grid[minI][minJ])
i = minI
j = minJ
k -= 1
}
return path
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(repeating: Array(repeating: Array(repeating: 0, count: n * m + 1), count: n * m + 1), count: n * m + 1)
for i in 0..<n {
for j in 0..<m {
for k in 0..<n * m {
d[i][j][k] = -1
}
}
}
func dfs(i: Int, j: Int, k: Int) -> Int {
if k == 0 {
return 0
}
if d[i][j][k] != -1 {
return d[i][j][k]
}
var res = Int.max
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
res = min(res, dfs(i: x, j: y, k: k - 1) + abs(grid[i][j] - grid[x][y]))
}
}
d[i][j][k] = res
return res
}
let res = dfs(i: 0, j: 0, k: k)
var path = [Int]()
var i = 0, j = 0, k = k
while k > 0 {
var minVal = Int.max
var minI = -1, minJ = -1
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < n && y >= 0 && y < m {
if d[x][y][k - 1] + abs(grid[i][j] - grid[x][y]) < minVal {
minVal = d[x][y][k - 1] + abs(grid[i][j] - grid[x][y])
minI = x
minJ = y
}
}
}
path.append(grid[minI][minJ])
i = minI
j = minJ
k -= 1
}
return path
}
```
d[i][j][k] = -1 // cannot assign through subscript: 'd' is a 'let' constant
d[i][j][k] = res // cannot assign through subscript: 'd' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1...k {
for j in 0..<n {
for l in 0..<m {
dp[i][j][l] = Int.max
if j > 0 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j - 1][l])
}
if j < n - 1 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j + 1][l])
}
if l > 0 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l - 1])
}
if l < m - 1 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l + 1])
}
dp[i][j][l] += grid[j][l]
}
}
}
var res = [Int]()
var i = n - 1
var j = m - 1
var l = 0
for _ in 0..<k {
res.append(dp[k][i][l])
if i > 0 && dp[k][i - 1][l] < dp[k][i][l] {
i -= 1
} else if j > 0 && dp[k][i][j - 1] < dp[k][i][l] {
j -= 1
} else if l > 0 && dp[k][i][l - 1] < dp[k][i][l] {
l -= 1
} else {
i -= 1
}
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[0][i][j] = grid[i][j]
}
}
for i in 1...k {
for j in 0..<n {
for l in 0..<m {
dp[i][j][l] = Int.max
if j > 0 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j - 1][l])
}
if j < n - 1 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j + 1][l])
}
if l > 0 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l - 1])
}
if l < m - 1 {
dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l + 1])
}
dp[i][j][l] += grid[j][l]
}
}
}
var res = [Int]()
var i = n - 1
var j = m - 1
var l = 0
for _ in 0..<k {
res.append(dp[k][i][l])
if i > 0 && dp[k][i - 1][l] < dp[k][i][l] {
i -= 1
} else if j > 0 && dp[k][i][j - 1] < dp[k][i][l] {
j -= 1
} else if l > 0 && dp[k][i][l - 1] < dp[k][i][l] {
l -= 1
} else {
i -= 1
}
}
return res
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
}
```
} // missing return in global function expected to return '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(1...n*m)
let s = Array(1...k)
let dp = Array(repeating: Array(repeating: Array(repeating: 0, count: k+1), count: n), count: m)
for i in 0..<n {
for j in 0..<m {
dp[i][j][0] = 1
}
}
for i in 0..<n {
for j in 0..<m {
for l in 1...k {
for v in d {
var cnt = 0
if i > 0 && dp[i-1][j][l-1] > 0 && v > grid[i-1][j] {
cnt += 1
}
if i < n-1 && dp[i+1][j][l-1] > 0 && v > grid[i+1][j] {
cnt += 1
}
if j > 0 && dp[i][j-1][l-1] > 0 && v > grid[i][j-1] {
cnt += 1
}
if j < m-1 && dp[i][j+1][l-1] > 0 && v > grid[i][j+1] {
cnt += 1
}
if cnt == 0 {
dp[i][j][l] = 1
}
}
}
}
}
var res = [Int]()
var i = 0
var j = 0
var l = k
while l > 0 {
var v = grid[i][j]
var cnt = 0
if i > 0 && dp[i-1][j][l-1] > 0 && v > grid[i-1][j] {
cnt += 1
}
if i < n-1 && dp[i+1][j][l-1] > 0 && v > grid[i+1][j] {
cnt += 1
}
if j > 0 && dp[i][j-1][l-1] > 0 && v > grid[i][j-1] {
cnt += 1
}
if j < m-1 && dp[i][j+1][l-1] > 0 && v > grid[i][j+1] {
cnt += 1
}
if cnt == 0 {
res.append(v)
l -= 1
} else {
var min_v = grid[i][j]
var min_i = i
var min_j = j
if i > 0 && dp[i-1][j][l-1] > 0 && grid[i-1][j] < min_v {
min_v = grid[i-1][j]
min_i = i-1
min_j = j
}
if i < n-1 && dp[i+1][j][l-1] > 0 && grid[i+1][j] < min_v {
min_v = grid[i+1][j]
min_i = i+1
min_j = j
}
if j > 0 && dp[i][j-1][l-1] > 0 && grid[i][j-1] < min_v {
min_v = grid[i][j-1]
min_i = i
min_j = j-1
}
if j < m-1 && dp[i][j+1][l-1] > 0 && grid[i][j+1] < min_v {
min_v = grid[i][j+1]
min_i = i
min_j = j+1
}
i = min_i
j = min_j
v = min_v
res.append(v)
l -= 1
}
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let d = Array(1...n*m)
let s = Array(1...k)
let dp = Array(repeating: Array(repeating: Array(repeating: 0, count: k+1), count: n), count: m)
for i in 0..<n {
for j in 0..<m {
dp[i][j][0] = 1
}
}
for i in 0..<n {
for j in 0..<m {
for l in 1...k {
for v in d {
var cnt = 0
if i > 0 && dp[i-1][j][l-1] > 0 && v > grid[i-1][j] {
cnt += 1
}
if i < n-1 && dp[i+1][j][l-1] > 0 && v > grid[i+1][j] {
cnt += 1
}
if j > 0 && dp[i][j-1][l-1] > 0 && v > grid[i][j-1] {
cnt += 1
}
if j < m-1 && dp[i][j+1][l-1] > 0 && v > grid[i][j+1] {
cnt += 1
}
if cnt == 0 {
dp[i][j][l] = 1
}
}
}
}
}
var res = [Int]()
var i = 0
var j = 0
var l = k
while l > 0 {
var v = grid[i][j]
var cnt = 0
if i > 0 && dp[i-1][j][l-1] > 0 && v > grid[i-1][j] {
cnt += 1
}
if i < n-1 && dp[i+1][j][l-1] > 0 && v > grid[i+1][j] {
cnt += 1
}
if j > 0 && dp[i][j-1][l-1] > 0 && v > grid[i][j-1] {
cnt += 1
}
if j < m-1 && dp[i][j+1][l-1] > 0 && v > grid[i][j+1] {
cnt += 1
}
if cnt == 0 {
res.append(v)
l -= 1
} else {
var min_v = grid[i][j]
var min_i = i
var min_j = j
if i > 0 && dp[i-1][j][l-1] > 0 && grid[i-1][j] < min_v {
min_v = grid[i-1][j]
min_i = i-1
min_j = j
}
if i < n-1 && dp[i+1][j][l-1] > 0 && grid[i+1][j] < min_v {
min_v = grid[i+1][j]
min_i = i+1
min_j = j
}
if j > 0 && dp[i][j-1][l-1] > 0 && grid[i][j-1] < min_v {
min_v = grid[i][j-1]
min_i = i
min_j = j-1
}
if j < m-1 && dp[i][j+1][l-1] > 0 && grid[i][j+1] < min_v {
min_v = grid[i][j+1]
min_i = i
min_j = j+1
}
i = min_i
j = min_j
v = min_v
res.append(v)
l -= 1
}
}
return res
}
```
dp[i][j][0] = 1 // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j][l] = 1 // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Array(repeating: Int.max, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[1][i][j] = grid[i][j]
}
}
for l in 2...k {
for i in 0..<n {
for j in 0..<m {
for x in max(0, i - 1)...min(n - 1, i + 1) {
for y in max(0, j - 1)...min(m - 1, j + 1) {
if x == i && y == j {
continue
}
dp[l][i][j] = min(dp[l][i][j], dp[l - 1][x][y] + grid[i][j])
}
}
}
}
}
var res = [Int]()
var i = 0
var j = 0
for l in (1...k).reversed() {
res.append(dp[l][i][j])
var minVal = Int.max
var minI = -1
var minJ = -1
for x in max(0, i - 1)...min(n - 1, i + 1) {
for y in max(0, j - 1)...min(m - 1, j + 1) {
if x == i && y == j {
continue
}
if dp[l - 1][x][y] + grid[i][j] < minVal {
minVal = dp[l - 1][x][y] + grid[i][j]
minI = x
minJ = y
}
}
}
i = minI
j = minJ
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
var dp = Array(repeating: Array(repeating: Array(repeating: Int.max, count: m), count: n), count: k + 1)
for i in 0..<n {
for j in 0..<m {
dp[1][i][j] = grid[i][j]
}
}
for l in 2...k {
for i in 0..<n {
for j in 0..<m {
for x in max(0, i - 1)...min(n - 1, i + 1) {
for y in max(0, j - 1)...min(m - 1, j + 1) {
if x == i && y == j {
continue
}
dp[l][i][j] = min(dp[l][i][j], dp[l - 1][x][y] + grid[i][j])
}
}
}
}
}
var res = [Int]()
var i = 0
var j = 0
for l in (1...k).reversed() {
res.append(dp[l][i][j])
var minVal = Int.max
var minI = -1
var minJ = -1
for x in max(0, i - 1)...min(n - 1, i + 1) {
for y in max(0, j - 1)...min(m - 1, j + 1) {
if x == i && y == j {
continue
}
if dp[l - 1][x][y] + grid[i][j] < minVal {
minVal = dp[l - 1][x][y] + grid[i][j]
minI = x
minJ = y
}
}
}
i = minI
j = minJ
}
return res
}
```
func tri(n: Int) -> [Int] {
var arr = [1, 3]
for i in 2...n {
if i % 2 == 0 {
arr.append(1 + i / 2)
} else {
arr.append(arr[i - 1] + arr[i - 2] + arr[i + 1])
}
}
return arr
}
```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 arr = [1, 3]
for i in 2...n {
if i % 2 == 0 {
arr.append(1 + i / 2)
} else {
arr.append(arr[i - 1] + arr[i - 2] + arr[i + 1])
}
}
return arr
}
print(tri(n: 3))
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 != 0 {
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 != 0 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 != 0 {
product *= digit
}
number /= 10
}
return product
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 != 0 {
product *= digit
}
number /= 10
}
return product
}
```
// 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 product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 != 0 {
product *= digit
}
number /= 10
}
return product
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 != 0 {
product *= digit
}
number /= 10
}
return product
}
```
// 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 != 0 {
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 != 0 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
product *= digit
}
number /= 10
}
return product
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
product *= digit
}
number /= 10
}
return product
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var num = n
var product = 1
while num > 0 {
let digit = num % 10
if digit % 2 != 0 {
product *= digit
}
num /= 10
}
return product
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var num = n
var product = 1
while num > 0 {
let digit = num % 10
if digit % 2 != 0 {
product *= digit
}
num /= 10
}
return product
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
product *= digit
}
number /= 10
}
return product
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 == 1 {
product *= digit
}
number /= 10
}
return product
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2 != 0 {
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 != 0 {
result *= digit
}
number /= 10
}
return result
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty || stack.removeLast() != "[" {
return false
}
}
}
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 || stack.removeLast() != "[" {
return false
}
}
}
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 {
let brackets = string.filter { $0 == "[" || $0 == "]" }
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
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
let brackets = string.filter { $0 == "[" || $0 == "]" }
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
}
```
// 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.popLast()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.popLast()
}
}
return stack.isEmpty
}
```
stack.popLast() // result of call to 'popLast()' is unused
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
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
} 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 = [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 = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty || stack.removeLast() != "[" {
return false
}
}
}
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 || stack.removeLast() != "[" {
return false
}
}
}
return stack.isEmpty
}
```
// 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 {
var sum: Int = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum: Int = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
let rounded = lst.map { ceil($0) }
let squared = rounded.map { $0 * $0 }
return squared.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 {
let rounded = lst.map { ceil($0) }
let squared = rounded.map { $0 * $0 }
return squared.reduce(0, +)
}
```
return squared.reduce(0, +) // cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Double) throws -> Int'
func sumSquares(lst: [Double]) -> Int {
return lst.map { Int(ceil($0)) * 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)) * Int(ceil($0)) }.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
let rounded = lst.map { Int(ceil($0)) }
let squared = rounded.map { $0 * $0 }
return squared.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 {
let rounded = lst.map { Int(ceil($0)) }
let squared = rounded.map { $0 * $0 }
return squared.reduce(0, +)
}
```
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```
func sumSquares(lst: [Double]) -> Int {
let rounded = lst.map { ceil($0) }
let squared = rounded.map { $0 * $0 }
let sum = squared.reduce(0, +)
return Int(sum)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
let rounded = lst.map { ceil($0) }
let squared = rounded.map { $0 * $0 }
let sum = squared.reduce(0, +)
return Int(sum)
}
```
func sumSquares(lst: [Double]) -> Int {
let squared = lst.map { Int(ceil($0)) * Int(ceil($0)) }
return squared.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 {
let squared = lst.map { Int(ceil($0)) * Int(ceil($0)) }
return squared.reduce(0, +)
}
```
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
} else {
return 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 {
let lastChar = txt.last
if lastChar == " " {
return false
} else {
return true
}
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = CharacterSet.letters.contains(lastChar!)
let isWord = txt.contains(" ")
if isLetter && !isWord {
return true
} else {
return false
}
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = CharacterSet.letters.contains(lastChar!)
let isWord = txt.contains(" ")
if isLetter && !isWord {
return true
} else {
return false
}
}
```
let isLetter = CharacterSet.letters.contains(lastChar!) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'Unicode.Scalar'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let lastCharIsLetter = lastChar?.isLetter ?? false
let lastCharIsSpace = lastChar?.isWhitespace ?? false
return lastCharIsLetter && !lastCharIsSpace
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let lastCharIsLetter = lastChar?.isLetter ?? false
let lastCharIsSpace = lastChar?.isWhitespace ?? false
return lastCharIsLetter && !lastCharIsSpace
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = CharacterSet.letters.contains(lastChar!)
let isNotPartOfWord = txt.last == " "
return isLetter && isNotPartOfWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = CharacterSet.letters.contains(lastChar!)
let isNotPartOfWord = txt.last == " "
return isLetter && isNotPartOfWord
}
```
let isLetter = CharacterSet.letters.contains(lastChar!) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'Unicode.Scalar'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = CharacterSet.letters.contains(lastChar!)
let isWord = txt.contains(" ")
if isLetter && !isWord {
return true
} else {
return false
}
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
let isLetter = CharacterSet.letters.contains(lastChar!)
let isWord = txt.contains(" ")
if isLetter && !isWord {
return true
} else {
return false
}
}
```
let isLetter = CharacterSet.letters.contains(lastChar!) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'Unicode.Scalar'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let words = txt.split(separator: " ")
let lastWord = words.last ?? ""
let lastCharacter = lastWord.last ?? " "
return lastCharacter.isLetter && lastWord.count > 1
}
```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 words = txt.split(separator: " ")
let lastWord = words.last ?? ""
let lastCharacter = lastWord.last ?? " "
return lastCharacter.isLetter && lastWord.count > 1
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if lastChar == nil {
return false
}
if lastChar!.isLetter {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if lastChar == nil {
return false
}
if lastChar!.isLetter {
return true
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if lastChar == "e" {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
}
if lastChar == "e" {
return true
}
return false
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last
if lastChar == " " {
return false
} else {
return 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 {
let lastChar = txt.last
if lastChar == " " {
return false
} else {
return true
}
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let words = txt.components(separatedBy: " ")
let lastWord = words.last ?? ""
let lastChar = lastWord.last ?? Character("")
return lastChar.isLetter && lastWord.count > 1
}
```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 words = txt.components(separatedBy: " ")
let lastWord = words.last ?? ""
let lastChar = lastWord.last ?? Character("")
return lastChar.isLetter && lastWord.count > 1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i + 1] {
maxIndex = i
}
}
return maxIndex
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i + 1] {
maxIndex = i
}
}
return maxIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var max = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] > arr[i-1] {
max = i-1
}
}
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 i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] > arr[i-1] {
max = i-1
}
}
return max
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i + 1] {
maxIndex = i
}
}
return maxIndex
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i + 1] {
maxIndex = i
}
}
return maxIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count {
if i > 0 && arr[i] <= arr[i - 1] {
maxIndex = i
}
}
return maxIndex
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count {
if i > 0 && arr[i] <= arr[i - 1] {
maxIndex = i
}
}
return maxIndex
}
```
func canArrange(arr: [Int]) -> Int {
var max = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = 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 = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = i
}
}
return max
}
```
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i + 1] {
maxIndex = i
}
}
return maxIndex
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var maxIndex = -1
for i in 0..<arr.count - 1 {
if arr[i] < arr[i + 1] {
maxIndex = i
}
}
return maxIndex
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var max = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = 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 = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = i
}
}
return max
}
```
func canArrange(arr: [Int]) -> Int {
var max = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = 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 = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = i
}
}
return max
}
```
func canArrange(arr: [Int]) -> Int {
var max = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = 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 = -1
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] <= arr[i - 1] {
max = i
}
}
return max
}
```
func canArrange(arr: [Int]) -> Int {
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] > arr[i-1] {
return i - 1
}
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
for i in 0..<arr.count {
if i == 0 {
continue
}
if arr[i] > arr[i-1] {
return i - 1
}
}
return -1
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
if negative.isEmpty && positive.isEmpty {
return (nil, nil)
} else if negative.isEmpty {
return (nil, positive.min())
} else if positive.isEmpty {
return (negative.max(), nil)
} else {
return (negative.max(), positive.min())
}
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
if negative.isEmpty && positive.isEmpty {
return (nil, nil)
} else if negative.isEmpty {
return (nil, positive.min())
} else if positive.isEmpty {
return (negative.max(), nil)
} else {
return (negative.max(), positive.min())
}
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for i in lst {
if i < 0 {
if largest == nil || i > largest! {
largest = i
}
} else if i > 0 {
if smallest == nil || i < smallest! {
smallest = i
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for i in lst {
if i < 0 {
if largest == nil || i > largest! {
largest = i
}
} else if i > 0 {
if smallest == nil || i < smallest! {
smallest = i
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let positive = lst.filter { $0 > 0 }
let negative = lst.filter { $0 < 0 }
let smallestPositive = positive.min()
let largestNegative = negative.max()
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?) {
let positive = lst.filter { $0 > 0 }
let negative = lst.filter { $0 < 0 }
let smallestPositive = positive.min()
let largestNegative = negative.max()
return (largestNegative, smallestPositive)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int? = nil
var smallest: Int? = nil
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var largest: Int?
var smallest: Int?
for num in lst {
if num < 0 {
if largest == nil || num > largest! {
largest = num
}
} else if num > 0 {
if smallest == nil || num < smallest! {
smallest = num
}
}
}
return (largest, smallest)
}
```
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b && a > c ? a : b > c ? b : c
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b && a > c ? a : b > c ? b : c
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b && a > c ? a : b > c ? b : c
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes three 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), c: .stringValue("3,4")) == .stringValue("3,4")
// compareThree(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3,4")) == .stringValue("3,4")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7")) == .stringValue("7")
// compareThree(a: .stringValue("1"), b: .intValue(1), c: .stringValue("2,3")) == .stringValue("2,3")
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b && a > c ? a : b > c ? b : c
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b && a > c ? a : b > c ? b : c
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b && a > c ? a : b > c ? b : c
default:
return nil
}
}
// Create a function that takes four 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), c: .stringValue("3,4"), d: .stringValue("4,5")) == .stringValue("4,5")
// compareFour(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3,4"), d: .stringValue("4,5")) == .stringValue("4,5")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7"), d: .stringValue("8")) == .stringValue("8")
// compareFour(a: .stringValue("1"), b: .intValue(1), c: .stringValue("2,3"), d: .stringValue("3,4")) == .stringValue("3,4")
func compareFour(a: Value, b: Value, c: Value, d: Value) -> Value? {
switch (a, b, c, d) {
case (.intValue(let a), .intValue(let b), .
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b && a > c ? a : b > c ? b : c // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b && a > c ? a : b > c ? b : c // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b && a > c ? a : b > c ? b : c // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b ? a : b > c ? b : c
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b ? a : b > c ? b : c
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b ? a : b > c ? b : c
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes three 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), c: .stringValue("3")) == .stringValue("3")
// compareThree(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3")) == .stringValue("3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7")) == .stringValue("7")
// compareThree(a: .stringValue("1"), b: .intValue(1), c: .stringValue("2")) == nil
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b ? a : b > c ? b : c
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b ? a : b > c ? b : c
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b ? a : b > c ? b : c
default:
return nil
}
}
// Create a function that takes four 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), c: .stringValue("3"), d: .stringValue("4")) == .stringValue("4")
// compareFour(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3"), d: .stringValue("4")) == .stringValue("4")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7"), d: .stringValue("8")) == .stringValue("8")
// compareFour(a: .stringValue("1"), b: .intValue(1), c: .stringValue("2"), d: .stringValue("3")) == nil
func compareFour(a: Value, b: Value, c: Value, d: Value) -> Value? {
switch (a, b, c, d) {
case (.intValue(let a), .intValue(let b), .intValue(let c), .intValue(let d)):
return a > b ? a :
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b > c ? b : c // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b > c ? b : c // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b > c ? b : c // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b ? (a > c ? a : c) : (b > c ? b : c)
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b ? (a > c ? a : c) : (b > c ? b : c)
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b ? (a > c ? a : c) : (b > c ? b : c)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes three 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), c: .stringValue("3,4")) == .stringValue("3,4")
// compareThree(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3,4")) == .stringValue("3,4")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7")) == .stringValue("7")
// compareThree(a: .stringValue("1"), b: .intValue(1), c: .doubleValue(1)) == nil
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b ? (a > c ? a : c) : (b > c ? b : c)
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b ? (a > c ? a : c) : (b > c ? b : c)
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b ? (a > c ? a : c) : (b > c ? b : c)
default:
return nil
}
}
// Create a function that takes four 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), c: .stringValue("3,4"), d: .stringValue("4,5")) == .stringValue("4,5")
// compareFour(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3,4"), d: .stringValue("4,5")) == .stringValue("4,5")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7"), d: .stringValue("8")) == .stringValue("8")
// compareFour(a: .stringValue("1"), b: .intValue(1), c: .doubleValue(1), d: .stringValue("4,5")) == nil
func compareFour(a: Value, b: Value, c: Value, d: Value) -> Value? {
switch (a, b, c, d) {
case (.intValue(let a), .intValue(let b
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? (a > c ? a : c) : (b > c ? b : c) // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? (a > c ? a : c) : (b > c ? b : c) // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? (a > c ? a : c) : (b > c ? b : c) // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareThree(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareThree(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareThree(a: .stringValue("1"), b: .intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareFour(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareFour(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareFour(a: .stringValue("1"), b: .intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two 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")) ==
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b ? a > c ? a : c : b > c ? b : c
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b ? a > c ? a : c : b > c ? b : c
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b ? a > c ? a : c : b > c ? b : c
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes three 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), c: .stringValue("3,4")) == .stringValue("3,4")
// compareThree(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3,4")) == .stringValue("3,4")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7")) == .stringValue("7")
// compareThree(a: .stringValue("1"), b: .intValue(1), c: .stringValue("3,4")) == nil
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let a), .intValue(let b), .intValue(let c)):
return a > b ? a > c ? a : c : b > c ? b : c
case (.doubleValue(let a), .doubleValue(let b), .doubleValue(let c)):
return a > b ? a > c ? a : c : b > c ? b : c
case (.stringValue(let a), .stringValue(let b), .stringValue(let c)):
return a > b ? a > c ? a : c : b > c ? b : c
default:
return nil
}
}
// Create a function that takes four 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), c: .stringValue("3,4"), d: .stringValue("4,5")) == .stringValue("4,5")
// compareFour(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3,4"), d: .stringValue("4,5")) == .stringValue("4,5")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7"), d: .stringValue("8")) == .stringValue("8")
// compareFour(a: .stringValue("1"), b: .intValue(1), c: .stringValue("3,4"), d: .stringValue("4,5")) == nil
func compareFour(a: Value, b: Value, c: Value, d: Value) -> Value? {
switch (a, b, c, d) {
case (.intValue(let a), .intValue(let b), .intValue(let c), .
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a > c ? a : c : b > c ? b : c // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a > c ? a : c : b > c ? b : c // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a > c ? a : c : b > c ? b : c // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareThree(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareThree(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareThree(a: .stringValue("1"), b: .intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareFour(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareFour(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareFour(a: .stringValue("1"), b: .intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes 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.
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareThree(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareThree(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareThree(a: .stringValue("1"), b: .intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareFour(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareFour(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareFour(a: .stringValue("1"), b: .intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two 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
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareThree(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareThree(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareThree(a: .stringValue("1"), b: .intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareFour(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareFour(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareFour(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareFour(a: .stringValue("1"), b: .intValue(1)) == nil
func compareFour(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two 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: .
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString) ?? 0 > Double(bString) ?? 0 ? a : Double(bString) ?? 0 > Double(aString) ?? 0 ? b : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString) ?? 0 > Double(bString) ?? 0 ? a : Double(bString) ?? 0 > Double(aString) ?? 0 ? b : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString) ?? 0 > Double(bString) ?? 0 ? a : Double(bString) ?? 0 > Double(aString) ?? 0 ? b : nil
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString) ?? 0 > Double(bString) ?? 0 ? a : Double(bString) ?? 0 > Double(aString) ?? 0 ? b : nil
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString) ?? 0 > Double(bString) ?? 0 ? a : Double(bString) ?? 0 > Double(aString) ?? 0 ? b : nil
default:
return nil
}
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareThree(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareThree(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareThree(a: .stringValue("1"), b: .intValue(1)) == nil
func compareThree(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
return Double(aString) ?? 0 > Double(bString) ?? 0 ? a : Double(bString) ?? 0 > Double(aString) ?? 0 ? 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
// XCTAssertTrue failed
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
let aDouble = Double(aString.replacingOccurrences(of: ",", with: ".")) ?? 0
let bDouble = Double(bString.replacingOccurrences(of: ",", with: ".")) ?? 0
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
let aDouble = Double(aString.replacingOccurrences(of: ",", with: ".")) ?? 0
let bDouble = Double(bString.replacingOccurrences(of: ",", with: ".")) ?? 0
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
default:
return nil
}
}
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let aInt), .intValue(let bInt), .intValue(let cInt)):
return aInt > bInt ? a : bInt > aInt ? b : cInt > aInt ? c : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble), .doubleValue(let cDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : cDouble > aDouble ? c : nil
case (.stringValue(let aString), .stringValue(let bString), .stringValue(let cString)):
let aDouble = Double(aString.replacingOccurrences(of: ",", with: ".")) ?? 0
let bDouble = Double(bString.replacingOccurrences(of: ",", with: ".")) ?? 0
let cDouble = Double(cString.replacingOccurrences(of: ",", with: ".")) ?? 0
return aDouble > bDouble ? a : bDouble > aDouble ? b : cDouble > aDouble ? c : nil
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
let aDouble = Double(aString.replacingOccurrences(of: ",", with: ".")) ?? 0
let bDouble = Double(bString.replacingOccurrences(of: ",", with: ".")) ?? 0
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
default:
return nil
}
}
// Create a function that takes two 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 aInt), .intValue(let bInt)):
return aInt > bInt ? a : bInt > aInt ? b : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
case (.stringValue(let aString), .stringValue(let bString)):
let aDouble = Double(aString.replacingOccurrences(of: ",", with: ".")) ?? 0
let bDouble = Double(bString.replacingOccurrences(of: ",", with: ".")) ?? 0
return aDouble > bDouble ? a : bDouble > aDouble ? b : nil
default:
return nil
}
}
// Create a function that takes three 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), c: .stringValue("3")) == .stringValue("3")
// compareThree(a: .intValue(1), b: .stringValue("2,3"), c: .stringValue("3")) == .stringValue("3")
// compareThree(a: .stringValue("5,1"), b: .stringValue("6"), c: .stringValue("7")) == .stringValue("7")
// compareThree(a: .stringValue("1"), b: .intValue(1), c: .stringValue("1")) == nil
func compareThree(a: Value, b: Value, c: Value) -> Value? {
switch (a, b, c) {
case (.intValue(let aInt), .intValue(let bInt), .intValue(let cInt)):
return aInt > bInt ? a : bInt > aInt ? b : cInt > aInt ? c : nil
case (.doubleValue(let aDouble), .doubleValue(let bDouble), .doubleValue(let cDouble)):
return aDouble > bDouble ? a : bDouble > aDouble ? b : cDouble > aDouble ? c : nil
case (.stringValue(let aString), .stringValue(let bString), .stringValue(let cString)):
let aDouble = Double(aString.replacingOccurrences(of: ",", with: ".")) ?? 0
let bDouble = Double(bString.replacingOccurrences(of: ",", with: ".")) ?? 0
let cDouble = Double(cString.replacingOccurrences(of: ",", with: ".")) ?? 0
return aDouble > bDouble ? a : bDouble > aDouble ? b : cDouble > aDouble ? c : nil
default:
return nil
}
}
// Create a function that takes four real numbers, and returns the larger variable in its given variable type
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
if n % 2 != 0 {
return false
}
for i in 1...n {
for j in i...n {
for k in j...n {
for l in k...n {
if i + j + k + l == 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 {
if n % 2 != 0 {
return false
}
for i in 1...n {
for j in i...n {
for k in j...n {
for l in k...n {
if i + j + k + l == n {
return true
}
}
}
}
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var count = 0
var i = 0
while count < 4 {
if n % 2 == 0 {
count += 1
n -= i
i += 2
} else {
return false
}
}
return true
}
```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 count = 0
var i = 0
while count < 4 {
if n % 2 == 0 {
count += 1
n -= i
i += 2
} else {
return false
}
}
return true
}
```
n -= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func isEqualToSumEven(n: Int) -> Bool {
// your code here
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 {
// your code here
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
if n % 2 != 0 {
return false
}
for i in 1...n/2 {
for j in i...n/2 {
for k in j...n/2 {
for l in k...n/2 {
if i + j + k + l == 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 {
if n % 2 != 0 {
return false
}
for i in 1...n/2 {
for j in i...n/2 {
for k in j...n/2 {
for l in k...n/2 {
if i + j + k + l == n {
return true
}
}
}
}
}
return false
}
print(isEqualToSumEven(n: 4))
print(isEqualToSumEven(n: 6))
print(isEqualToSumEven(n: 8))
print(isEqualToSumEven(n: 10))
print(isEqualToSumEven(n: 12))
print(isEqualToSumEven(n: 14))
print(isEqualToSumEven(n: 16))
print(isEqualToSumEven(n: 18))
print(isEqualToSumEven(n: 20))
print(isEqualToSumEven(n: 22))
print(isEqualToSumEven(n: 24))
print(isEqualToSumEven(n: 26))
print(isEqualToSumEven(n: 28))
print(isEqualToSumEven(n: 30))
print(isEqualToSumEven(n: 32))
print(isEqualToSumEven(n: 34))
print(isEqualToSumEven(n: 36))
print(isEqualToSumEven(n: 38))
print(isEqualToSumEven(n: 40))
print(isEqualToSumEven(n: 42))
print(isEqualToSumEven(n: 44))
print(isEqualToSumEven(n: 46))
print(isEqualToSumEven(n: 48))
print(isEqualToSumEven(n: 50))
print(isEqualToSumEven(n: 52))
print(isEqualToSumEven(n: 54))
print(isEqualToSumEven(n: 56))
print(isEqualToSumEven(n: 58))
print(isEqualToSumEven(n: 60))
print(isEqualToSumEven(n: 62))
print(isEqualToSumEven(n: 64))
print(isEqualToSumEven(n: 66))
print(isEqualToSumEven(n: 68))
print(isEqualToSumEven(n: 70))
print(isEqualToSumEven(n: 72))
print(isEqualToSumEven(n: 74))
print(isEqualToSumEven(n: 76))
print(isEqualToSumEven(n: 78))
print(isEqualToSumEven(n: 80))
print(isEqualToSumEven(n: 82))
print(isEqualToSumEven(n: 84))
print(isEqualToSumEven(n: 86))
print(isEqualToSumEven(n: 88))
print(isEqualToSumEven(n: 90))
print(isEqualToSumEven(n: 92))
print(isEqualToSumEven(n: 94))
print(isEqualToSumEven(n: 96))
print(isEqualToSumEven(n: 98))
print(isEqualToSumEven(n: 100))
print(isEqualToSumEven(n: 102))
print(isEqualToSumEven(n: 104))
print(isEqualToSumEven(n: 106))
print(isEqualToSumEven(n: 108))
print(isEqualToSumEven(n: 110))
print(isEqualToSumEven(n: 112))
print(isEqualToSumEven(n: 114))
print(isEqualToSumEven(n: 116))
print(isEqualToSumEven(n: 118))
print(isEqualToSumEven(n: 120))
print(isEqualToSumEven(n: 122))
print(isEqualToSumEven(n: 124))
print(isEqualToSumEven(n: 126))
print(isEqualToSumEven(n: 128))
print(isEqualToSumEven(n: 130))
print(isEqualToSumEven(n: 132))
print(isEqualToSumEven(n: 134))
print(isEqualToSumEven(n: 136))
print(isEqualToSumEven(n: 138))
print(isEqualToSumEven(n: 140))
print(isEqualTo
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// TODO: Write your code here
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 {
// TODO: Write your code here
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
if n % 2 != 0 {
return false
}
for i in 0..<n {
for j in 0..<n {
for k in 0..<n {
for l in 0..<n {
if i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
if i + j + k + l == 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 {
if n % 2 != 0 {
return false
}
for i in 0..<n {
for j in 0..<n {
for k in 0..<n {
for l in 0..<n {
if i % 2 == 0 && j % 2 == 0 && k % 2 == 0 && l % 2 == 0 {
if i + j + k + l == n {
return true
}
}
}
}
}
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// TODO: Implement this function
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 {
// TODO: Implement this function
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// your code here
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 {
// your code here
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// TODO: Your code here
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 {
// TODO: Your code here
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
// TODO: Write your code here
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 {
// TODO: Write your code here
return false
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= 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
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// The function will
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= factorial(n: i)
}
return result
}
func factorial(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 *= factorial(n: i)
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
print(specialFactorial(n: 4))
```
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 factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will receive an integer as input and should return the factorial
// of this integer.
// factorial(n: 4) == 24
func factorial(n: Int) -> Int {
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
// The function will
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
if n <= 0 {
return 0
}
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
if n <= 0 {
return 0
}
var factorial = 1
for i in 1...n {
factorial *= i
}
return factorial
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
count = 0
result += String(i)
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
count = 0
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
count = 0
result += String(i)
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
count = 0
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 1 {
result += "-"
count = 0
} else {
result += "_"
count = 0
}
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 1 {
result += "-"
count = 0
} else {
result += "_"
count = 0
}
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 1 {
result += "-"
count = 0
} else if count == 1 {
result += "_"
count = 0
} else {
result += String(i)
}
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 1 {
result += "-"
count = 0
} else if count == 1 {
result += "_"
count = 0
} else {
result += String(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
count = 0
result += String(i)
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count == 1 {
result += "_"
} else if count > 1 {
result += "-"
}
count = 0
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else if count == 1 {
result += "_"
}
count = 0
}
result += String(i)
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else if count == 1 {
result += "_"
}
count = 0
}
result += String(i)
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 2 {
result += "-"
} else {
for _ in 0..<count {
result += "_"
}
}
count = 0
result += String(i)
}
}
if count > 2 {
result += "-"
} else {
for _ in 0..<count {
result += "_"
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
} else {
if count > 2 {
result += "-"
} else {
for _ in 0..<count {
result += "_"
}
}
count = 0
result += String(i)
}
}
if count > 2 {
result += "-"
} else {
for _ in 0..<count {
result += "_"
}
}
return result
}
```
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else if count == 1 {
result += "_"
}
count = 0
result += String(char)
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 1 {
result += "-"
} else if count == 1 {
result += "_"
}
count = 0
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
if count == 1 {
result += "_"
} else if count == 2 {
result += "-"
}
} else {
result += String(i)
count = 0
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
if count == 1 {
result += "_"
} else if count == 2 {
result += "-"
}
} else {
result += String(i)
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
if count == 1 {
result += "_"
} else if count == 2 {
result += "-"
}
} else {
count = 0
result += String(i)
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for i in text {
if i == " " {
count += 1
if count == 1 {
result += "_"
} else if count == 2 {
result += "-"
}
} else {
count = 0
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
let fileNameArray2 = fileNameArray[0].components(separatedBy: "")
let fileNameArray3 = fileNameArray[1].components(separatedBy: "")
var count = 0
for i in fileNameArray2 {
if i.isNumber {
count += 1
}
}
if fileNameArray.count == 2 && fileNameArray3.count == 3 && fileNameArray2[0].isLetter && count <= 3 && fileNameArray3 == ["t","x","t"] || fileNameArray3 == ["e","x","e"] || fileNameArray3 == ["d","l","l"] {
return "Yes"
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
let fileNameArray2 = fileNameArray[0].components(separatedBy: "")
let fileNameArray3 = fileNameArray[1].components(separatedBy: "")
var count = 0
for i in fileNameArray2 {
if i.isNumber {
count += 1
}
}
if fileNameArray.count == 2 && fileNameArray3.count == 3 && fileNameArray2[0].isLetter && count <= 3 && fileNameArray3 == ["t","x","t"] || fileNameArray3 == ["e","x","e"] || fileNameArray3 == ["d","l","l"] {
return "Yes"
} else {
return "No"
}
}
```
if i.isNumber { // value of type 'String' has no member 'isNumber'
if fileNameArray.count == 2 && fileNameArray3.count == 3 && fileNameArray2[0].isLetter && count <= 3 && fileNameArray3 == ["t","x","t"] || fileNameArray3 == ["e","x","e"] || fileNameArray3 == ["d","l","l"] { // value of type 'String' has no member 'isLetter'
func fileNameCheck(fileName: String) -> String {
let dot = "."
let txt = "txt"
let exe = "exe"
let dll = "dll"
if fileName.contains(dot) {
let split = fileName.split(separator: dot)
let first = String(split[0])
let second = String(split[1])
if first.contains(where: { $0.isLetter }) {
if second == txt || second == exe || second == dll {
if first.contains(where: { $0.isNumber }) {
if first.filter({ $0.isNumber }).count > 3 {
return "No"
} else {
return "Yes"
}
} else {
return "Yes"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let dot = "."
let txt = "txt"
let exe = "exe"
let dll = "dll"
if fileName.contains(dot) {
let split = fileName.split(separator: dot)
let first = String(split[0])
let second = String(split[1])
if first.contains(where: { $0.isLetter }) {
if second == txt || second == exe || second == dll {
if first.contains(where: { $0.isNumber }) {
if first.filter({ $0.isNumber }).count > 3 {
return "No"
} else {
return "Yes"
}
} else {
return "Yes"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```
// XCTAssertTrue failed
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let dotIndex = fileName.firstIndex(of: ".")
let dotIndex2 = fileName.firstIndex(of: ".")
let dotIndex3 = fileName.firstIndex(of: ".")
let dotIndex4 = fileName.firstIndex(of: ".")
let dotIndex5 = fileName.firstIndex(of: ".")
let dotIndex6 = fileName.firstIndex(of: ".")
let dotIndex7 = fileName.firstIndex(of: ".")
let dotIndex8 = fileName.firstIndex(of: ".")
let dotIndex9 = fileName.firstIndex(of: ".")
let dotIndex10 = fileName.firstIndex(of: ".")
let dotIndex11 = fileName.firstIndex(of: ".")
let dotIndex12 = fileName.firstIndex(of: ".")
let dotIndex13 = fileName.firstIndex(of: ".")
let dotIndex14 = fileName.firstIndex(of: ".")
let dotIndex15 = fileName.firstIndex(of: ".")
let dotIndex16 = fileName.firstIndex(of: ".")
let dotIndex17 = fileName.firstIndex(of: ".")
let dotIndex18 = fileName.firstIndex(of: ".")
let dotIndex19 = fileName.firstIndex(of: ".")
let dotIndex20 = fileName.firstIndex(of: ".")
let dotIndex21 = fileName.firstIndex(of: ".")
let dotIndex22 = fileName.firstIndex(of: ".")
let dotIndex23 = fileName.firstIndex(of: ".")
let dotIndex24 = fileName.firstIndex(of: ".")
let dotIndex25 = fileName.firstIndex(of: ".")
let dotIndex26 = fileName.firstIndex(of: ".")
let dotIndex27 = fileName.firstIndex(of: ".")
let dotIndex28 = fileName.firstIndex(of: ".")
let dotIndex29 = fileName.firstIndex(of: ".")
let dotIndex30 = fileName.firstIndex(of: ".")
let dotIndex31 = fileName.firstIndex(of: ".")
let dotIndex32 = fileName.firstIndex(of: ".")
let dotIndex33 = fileName.firstIndex(of: ".")
let dotIndex34 = fileName.firstIndex(of: ".")
let dotIndex35 = fileName.firstIndex(of: ".")
let dotIndex36 = fileName.firstIndex(of: ".")
let dotIndex37 = fileName.firstIndex(of: ".")
let dotIndex38 = fileName.firstIndex(of: ".")
let dotIndex39 = fileName.firstIndex(of: ".")
let dotIndex40 = fileName.firstIndex(of: ".")
let dotIndex41 = fileName.firstIndex(of: ".")
let dotIndex42 = fileName.firstIndex(of: ".")
let dotIndex43 = fileName.firstIndex(of: ".")
let dotIndex44 = fileName.firstIndex(of: ".")
let dotIndex45 = fileName.firstIndex(of: ".")
let dotIndex46 = fileName.firstIndex(of: ".")
let dotIndex47 = fileName.firstIndex(of: ".")
let dotIndex48 = fileName.firstIndex(of: ".")
let dotIndex49 = fileName.firstIndex(of: ".")
let dotIndex50 = fileName.firstIndex(of: ".")
let dotIndex51 = fileName.firstIndex(of: ".")
let dotIndex52 = fileName.firstIndex(of: ".")
let dotIndex53 = fileName.firstIndex(of: ".")
let dotIndex54 = fileName.firstIndex(of: ".")
let dotIndex55 = fileName.firstIndex(of: ".")
let dotIndex56 = fileName.firstIndex(of: ".")
let dotIndex57 = fileName.firstIndex(of: ".")
let dotIndex58 = fileName.firstIndex(of: ".")
let dotIndex59 = fileName.firstIndex(of: ".")
let dotIndex60 = fileName.firstIndex(of: ".")
let dot
XCTAssertTrue(fileNameCheck(fileName: "example.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1example.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s1sdf3.asd") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "K.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "MY16FILE3.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "His12FILE94.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "_Y.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "?aREYA.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "/thisIsValid.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.wow") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txtexe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "#this2I4s5valid.ten") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "@this1Is6Valid.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIs12valid.6exe4.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "all.exe.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_No.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "Is3youfault.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "noOne#knows.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1I563_Yes3.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_Yes3.txtt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final..txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final132") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "F4indsartal132.") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: ".txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s.") == "No") // cannot find 'fileNameCheck' in scope
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let dot = fileName.firstIndex(of: ".")!
let beforeDot = fileName[..<dot]
let afterDot = fileName[fileName.index(dot, offsetBy: 1)..<fileName.endIndex]
let digits = fileName.filter { $0.isNumber }
let letters = fileName.filter { $0.isLetter }
if digits.count > 3 || fileName.count == 0 || fileName.count == 1 || fileName.count == 2 || fileName.count == 3 || fileName.count == 4 || fileName.count == 5 || fileName.count == 6 || fileName.count == 7 || fileName.count == 8 || fileName.count == 9 || fileName.count == 10 || fileName.count == 11 || fileName.count == 12 || fileName.count == 13 || fileName.count == 14 || fileName.count == 15 || fileName.count == 16 || fileName.count == 17 || fileName.count == 18 || fileName.count == 19 || fileName.count == 20 || fileName.count == 21 || fileName.count == 22 || fileName.count == 23 || fileName.count == 24 || fileName.count == 25 || fileName.count == 26 || fileName.count == 27 || fileName.count == 28 || fileName.count == 29 || fileName.count == 30 || fileName.count == 31 || fileName.count == 32 || fileName.count == 33 || fileName.count == 34 || fileName.count == 35 || fileName.count == 36 || fileName.count == 37 || fileName.count == 38 || fileName.count == 39 || fileName.count == 40 || fileName.count == 41 || fileName.count == 42 || fileName.count == 43 || fileName.count == 44 || fileName.count == 45 || fileName.count == 46 || fileName.count == 47 || fileName.count == 48 || fileName.count == 49 || fileName.count == 50 || fileName.count == 51 || fileName.count == 52 || fileName.count == 53 || fileName.count == 54 || fileName.count == 55 || fileName.count == 56 || fileName.count == 57 || fileName.count == 58 || fileName.count == 59 || fileName.count == 60 || fileName.count == 61 || fileName.count == 62 || fileName.count == 63 || fileName.count == 64 || fileName.count == 65 || fileName.count == 66 || fileName.count == 67 || fileName.count == 68 || fileName.count == 69 || fileName.count == 70 || fileName.count == 71 || fileName.count == 72 || fileName.count == 73 || fileName.count == 74 || fileName.count == 75 || fileName.count == 76 || fileName.count == 77 || fileName.count == 78 || fileName.count == 79 || fileName.count == 80 || fileName.count == 81 || fileName.count == 82 || fileName.count == 83 || fileName.count == 84 || fileName.count == 85 || fileName.count == 86 || fileName.count == 87 || fileName.count == 88 || fileName.count == 89 || fileName.count == 90 || fileName.count == 91 || fileName.count == 92 || fileName.count == 93 || fileName.count == 94 || fileName.count == 95 || fileName.count == 96 || fileName.count == 97 || fileName.count == 98 || fileName.count == 99 || fileName.count == 100 || fileName.count == 101 || fileName.count == 102 || fileName.count == 103 || fileName.count == 104 || fileName.count == 105 || fileName.count == 106 || fileName.count == 107 || fileName.count == 108 || fileName.count == 109 || fileName.count == 110 || fileName.count == 111 || fileName.count == 112 || fileName.count == 113 || fileName.count == 1
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 fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameBeforeDot = fileNameArray[0]
let fileNameAfterDot = fileNameArray[1]
let fileNameAfterDotArray = fileNameAfterDot.split(separator: ".")
let fileNameAfterDotString = String(fileNameAfterDotArray[0])
if fileNameAfterDotString == "txt" || fileNameAfterDotString == "exe" || fileNameAfterDotString == "dll" {
if fileNameBeforeDot.first?.isLetter == true {
if fileNameBeforeDot.contains("0") || fileNameBeforeDot.contains("1") || fileNameBeforeDot.contains("2") || fileNameBeforeDot.contains("3") || fileNameBeforeDot.contains("4") || fileNameBeforeDot.contains("5") || fileNameBeforeDot.contains("6") || fileNameBeforeDot.contains("7") || fileNameBeforeDot.contains("8") || fileNameBeforeDot.contains("9") {
if fileNameBeforeDot.count <= 3 {
return "Yes"
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameBeforeDot = fileNameArray[0]
let fileNameAfterDot = fileNameArray[1]
let fileNameAfterDotArray = fileNameAfterDot.split(separator: ".")
let fileNameAfterDotString = String(fileNameAfterDotArray[0])
if fileNameAfterDotString == "txt" || fileNameAfterDotString == "exe" || fileNameAfterDotString == "dll" {
if fileNameBeforeDot.first?.isLetter == true {
if fileNameBeforeDot.contains("0") || fileNameBeforeDot.contains("1") || fileNameBeforeDot.contains("2") || fileNameBeforeDot.contains("3") || fileNameBeforeDot.contains("4") || fileNameBeforeDot.contains("5") || fileNameBeforeDot.contains("6") || fileNameBeforeDot.contains("7") || fileNameBeforeDot.contains("8") || fileNameBeforeDot.contains("9") {
if fileNameBeforeDot.count <= 3 {
return "Yes"
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameBeforeDot = fileNameArray[0]
let fileNameAfterDot = fileNameArray[1]
if fileNameBeforeDot.count > 0 && fileNameBeforeDot.first!.isLetter && fileNameAfterDot.count == 3 && fileNameAfterDot == "txt" || fileNameAfterDot == "exe" || fileNameAfterDot == "dll" {
return "Yes"
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameBeforeDot = fileNameArray[0]
let fileNameAfterDot = fileNameArray[1]
if fileNameBeforeDot.count > 0 && fileNameBeforeDot.first!.isLetter && fileNameAfterDot.count == 3 && fileNameAfterDot == "txt" || fileNameAfterDot == "exe" || fileNameAfterDot == "dll" {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameArray2 = fileNameArray[0].split(separator: "")
let fileNameArray3 = fileNameArray[1].split(separator: "")
if fileNameArray.count == 2 && fileNameArray2.count > 0 && fileNameArray3.count == 3 && fileNameArray3[0] == "t" && fileNameArray3[1] == "x" && fileNameArray3[2] == "t" {
return "Yes"
} else if fileNameArray.count == 2 && fileNameArray2.count > 0 && fileNameArray3.count == 3 && fileNameArray3[0] == "e" && fileNameArray3[1] == "x" && fileNameArray3[2] == "e" {
return "Yes"
} else if fileNameArray.count == 2 && fileNameArray2.count > 0 && fileNameArray3.count == 3 && fileNameArray3[0] == "d" && fileNameArray3[1] == "l" && fileNameArray3[2] == "l" {
return "Yes"
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameArray2 = fileNameArray[0].split(separator: "")
let fileNameArray3 = fileNameArray[1].split(separator: "")
if fileNameArray.count == 2 && fileNameArray2.count > 0 && fileNameArray3.count == 3 && fileNameArray3[0] == "t" && fileNameArray3[1] == "x" && fileNameArray3[2] == "t" {
return "Yes"
} else if fileNameArray.count == 2 && fileNameArray2.count > 0 && fileNameArray3.count == 3 && fileNameArray3[0] == "e" && fileNameArray3[1] == "x" && fileNameArray3[2] == "e" {
return "Yes"
} else if fileNameArray.count == 2 && fileNameArray2.count > 0 && fileNameArray3.count == 3 && fileNameArray3[0] == "d" && fileNameArray3[1] == "l" && fileNameArray3[2] == "l" {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
let fileNameArray2 = fileNameArray[0].components(separatedBy: "")
let fileNameArray3 = fileNameArray[1].components(separatedBy: "")
var count = 0
for i in fileNameArray2 {
if i.contains("0") || i.contains("1") || i.contains("2") || i.contains("3") || i.contains("4") || i.contains("5") || i.contains("6") || i.contains("7") || i.contains("8") || i.contains("9") {
count += 1
}
}
if fileNameArray.count == 2 && fileNameArray3.count == 3 && fileNameArray2[0].contains("a") || fileNameArray2[0].contains("b") || fileNameArray2[0].contains("c") || fileNameArray2[0].contains("d") || fileNameArray2[0].contains("e") || fileNameArray2[0].contains("f") || fileNameArray2[0].contains("g") || fileNameArray2[0].contains("h") || fileNameArray2[0].contains("i") || fileNameArray2[0].contains("j") || fileNameArray2[0].contains("k") || fileNameArray2[0].contains("l") || fileNameArray2[0].contains("m") || fileNameArray2[0].contains("n") || fileNameArray2[0].contains("o") || fileNameArray2[0].contains("p") || fileNameArray2[0].contains("q") || fileNameArray2[0].contains("r") || fileNameArray2[0].contains("s") || fileNameArray2[0].contains("t") || fileNameArray2[0].contains("u") || fileNameArray2[0].contains("v") || fileNameArray2[0].contains("w") || fileNameArray2[0].contains("x") || fileNameArray2[0].contains("y") || fileNameArray2[0].contains("z") && fileNameArray3[0].contains("t") && fileNameArray3[1].contains("x") && fileNameArray3[2].contains("t") || fileNameArray3[0].contains("d") && fileNameArray3[1].contains("l") && fileNameArray3[2].contains("l") || fileNameArray3[0].contains("e") && fileNameArray3[1].contains("x") && fileNameArray3[2].contains("e") && count <= 3 {
return "Yes"
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
let fileNameArray2 = fileNameArray[0].components(separatedBy: "")
let fileNameArray3 = fileNameArray[1].components(separatedBy: "")
var count = 0
for i in fileNameArray2 {
if i.contains("0") || i.contains("1") || i.contains("2") || i.contains("3") || i.contains("4") || i.contains("5") || i.contains("6") || i.contains("7") || i.contains("8") || i.contains("9") {
count += 1
}
}
if fileNameArray.count == 2 && fileNameArray3.count == 3 && fileNameArray2[0].contains("a") || fileNameArray2[0].contains("b") || fileNameArray2[0].contains("c") || fileNameArray2[0].contains("d") || fileNameArray2[0].contains("e") || fileNameArray2[0].contains("f") || fileNameArray2[0].contains("g") || fileNameArray2[0].contains("h") || fileNameArray2[0].contains("i") || fileNameArray2[0].contains("j") || fileNameArray2[0].contains("k") || fileNameArray2[0].contains("l") || fileNameArray2[0].contains("m") || fileNameArray2[0].contains("n") || fileNameArray2[0].contains("o") || fileNameArray2[0].contains("p") || fileNameArray2[0].contains("q") || fileNameArray2[0].contains("r") || fileNameArray2[0].contains("s") || fileNameArray2[0].contains("t") || fileNameArray2[0].contains("u") || fileNameArray2[0].contains("v") || fileNameArray2[0].contains("w") || fileNameArray2[0].contains("x") || fileNameArray2[0].contains("y") || fileNameArray2[0].contains("z") && fileNameArray3[0].contains("t") && fileNameArray3[1].contains("x") && fileNameArray3[2].contains("t") || fileNameArray3[0].contains("d") && fileNameArray3[1].contains("l") && fileNameArray3[2].contains("l") || fileNameArray3[0].contains("e") && fileNameArray3[1].contains("x") && fileNameArray3[2].contains("e") && count <= 3 {
return "Yes"
} else {
return "No"
}
}
print(fileNameCheck(fileName: "example.txt"))
print(fileNameCheck(fileName: "1example.dll"))
print(fileNameCheck(fileName: "1example.exe"))
print(fileNameCheck(fileName: "1example.dll"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example.txt"))
print(fileNameCheck(fileName: "1example
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let dot = "."
let txt = "txt"
let exe = "exe"
let dll = "dll"
let numbers = "0123456789"
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if fileName.contains(dot) {
let split = fileName.split(separator: dot)
let first = String(split[0])
let second = String(split[1])
if first.contains(alphabet) {
if first.contains(numbers) {
if second.contains(txt) || second.contains(exe) || second.contains(dll) {
return "Yes"
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let dot = "."
let txt = "txt"
let exe = "exe"
let dll = "dll"
let numbers = "0123456789"
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if fileName.contains(dot) {
let split = fileName.split(separator: dot)
let first = String(split[0])
let second = String(split[1])
if first.contains(alphabet) {
if first.contains(numbers) {
if second.contains(txt) || second.contains(exe) || second.contains(dll) {
return "Yes"
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
} else {
return "No"
}
}
```
// XCTAssertTrue failed
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.split(separator: ".")
let fileNameArray2 = fileNameArray[0].split(separator: "")
let fileNameArray3 = fileNameArray[1].split(separator: "")
let fileNameArray4 = fileNameArray[1].split(separator: "")
let fileNameArray5 = fileNameArray[1].split(separator: "")
let fileNameArray6 = fileNameArray[1].split(separator: "")
let fileNameArray7 = fileNameArray[1].split(separator: "")
let fileNameArray8 = fileNameArray[1].split(separator: "")
let fileNameArray9 = fileNameArray[1].split(separator: "")
let fileNameArray10 = fileNameArray[1].split(separator: "")
let fileNameArray11 = fileNameArray[1].split(separator: "")
let fileNameArray12 = fileNameArray[1].split(separator: "")
let fileNameArray13 = fileNameArray[1].split(separator: "")
let fileNameArray14 = fileNameArray[1].split(separator: "")
let fileNameArray15 = fileNameArray[1].split(separator: "")
let fileNameArray16 = fileNameArray[1].split(separator: "")
let fileNameArray17 = fileNameArray[1].split(separator: "")
let fileNameArray18 = fileNameArray[1].split(separator: "")
let fileNameArray19 = fileNameArray[1].split(separator: "")
let fileNameArray20 = fileNameArray[1].split(separator: "")
let fileNameArray21 = fileNameArray[1].split(separator: "")
let fileNameArray22 = fileNameArray[1].split(separator: "")
let fileNameArray23 = fileNameArray[1].split(separator: "")
let fileNameArray24 = fileNameArray[1].split(separator: "")
let fileNameArray25 = fileNameArray[1].split(separator: "")
let fileNameArray26 = fileNameArray[1].split(separator: "")
let fileNameArray27 = fileNameArray[1].split(separator: "")
let fileNameArray28 = fileNameArray[1].split(separator: "")
let fileNameArray29 = fileNameArray[1].split(separator: "")
let fileNameArray30 = fileNameArray[1].split(separator: "")
let fileNameArray31 = fileNameArray[1].split(separator: "")
let fileNameArray32 = fileNameArray[1].split(separator: "")
let fileNameArray33 = fileNameArray[1].split(separator: "")
let fileNameArray34 = fileNameArray[1].split(separator: "")
let fileNameArray35 = fileNameArray[1].split(separator: "")
let fileNameArray36 = fileNameArray[1].split(separator: "")
let fileNameArray37 = fileNameArray[1].split(separator: "")
let fileNameArray38 = fileNameArray[1].split(separator: "")
let fileNameArray39 = fileNameArray[1].split(separator: "")
let fileNameArray40 = fileNameArray[1].split(separator: "")
let fileNameArray41 = fileNameArray[1].split(separator: "")
let fileNameArray42 = fileNameArray[1].split(separator: "")
let fileNameArray43 = fileNameArray[1].split(separator: "")
let fileNameArray44 = fileNameArray[1].split(separator: "")
let fileNameArray45 = fileNameArray[1].split(separator: "")
let fileNameArray46 = fileNameArray[1].split(separator: "")
let fileNameArray47 = fileNameArray[1].split(separator: "")
let fileNameArray48 = fileNameArray[1].split(separator: "")
let fileNameArray49 = fileNameArray[1].split(separator: "")
let fileNameArray50 = fileNameArray[1].split(separator: "")
let fileNameArray51 = fileNameArray[1].split(separator: "")
let fileNameArray52 = fileNameArray[1].split(separator: "")
let fileNameArray53 = fileNameArray[1].split(separator: "")
let fileNameArray54 = fileNameArray[1].split(separator: "")
let fileNameArray55 = fileNameArray[1].split(separator: "")
let fileNameArray56 = fileNameArray[1].split(separator: "")
let fileNameArray57 = fileNameArray[1].split(separator: "")
XCTAssertTrue(fileNameCheck(fileName: "example.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1example.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s1sdf3.asd") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "K.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "MY16FILE3.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "His12FILE94.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "_Y.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "?aREYA.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "/thisIsValid.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.wow") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txtexe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "#this2I4s5valid.ten") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "@this1Is6Valid.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIs12valid.6exe4.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "all.exe.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_No.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "Is3youfault.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "noOne#knows.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1I563_Yes3.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_Yes3.txtt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final..txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final132") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "F4indsartal132.") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: ".txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s.") == "No") // cannot find 'fileNameCheck' in scope
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ").map { String($0) }
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
let primeWords = words.filter { word in
let wordLength = word.count
return primes.contains(wordLength)
}
return primeWords.joined(separator: " ")
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ").map { String($0) }
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
let primeWords = words.filter { word in
let wordLength = word.count
return primes.contains(wordLength)
}
return primeWords.joined(separator: " ")
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if word.count % 2 != 0 {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespacesAndNewlines)
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if word.count % 2 != 0 {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespacesAndNewlines)
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var result = ""
for word in words {
if isPrime(number: word.count) {
result += word + " "
}
}
return result.trimmingCharacters(in: .whitespaces)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = [String]()
for word in words {
if isPrime(Int(word)!) {
primeWords.append(String(word))
}
}
return primeWords.joined(separator: " ")
}
func isPrime(_ num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = [String]()
for word in words {
if isPrime(Int(word)!) {
primeWords.append(String(word))
}
}
return primeWords.joined(separator: " ")
}
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 wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = [String]()
for word in words {
if isPrime(number: word.count) {
result.append(String(word))
}
}
return result.joined(separator: " ")
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = [String]()
for word in words {
if isPrime(number: word.count) {
result.append(String(word))
}
}
return result.joined(separator: " ")
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ").map { String($0) }
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
let primeWords = words.filter { word in
let wordLength = word.count
return primes.contains(wordLength)
}
return primeWords.joined(separator: " ")
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ").map { String($0) }
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
let primeWords = words.filter { word in
let wordLength = word.count
return primes.contains(wordLength)
}
return primeWords.joined(separator: " ")
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var primeWords = [String]()
for word in words {
if isPrime(word.count) {
primeWords.append(word)
}
}
return primeWords.joined(separator: " ")
}
func isPrime(_ num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.components(separatedBy: " ")
var primeWords = [String]()
for word in words {
if isPrime(word.count) {
primeWords.append(word)
}
}
return primeWords.joined(separator: " ")
}
func isPrime(_ num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = [String]()
for word in words {
if isPrime(number: word.count) {
primeWords.append(String(word))
}
}
return primeWords.joined(separator: " ")
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = [String]()
for word in words {
if isPrime(number: word.count) {
primeWords.append(String(word))
}
}
return primeWords.joined(separator: " ")
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
print(wordsInSentence(sentence: "This is a test"))
print(wordsInSentence(sentence: "lets go for swimming"))
```
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
if xProduct % nProduct == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
if xProduct % nProduct == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
}
return false
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
}
return false
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumerator2 = xNumerator * nDenominator
let xDenominator2 = xDenominator * nNumerator
if xNumerator2 % xDenominator2 == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumerator2 = xNumerator * nDenominator
let xDenominator2 = xDenominator * nNumerator
if xNumerator2 % xDenominator2 == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xResult = xNumerator * nDenominator
let nResult = nNumerator * xDenominator
if xResult % nResult == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xResult = xNumerator * nDenominator
let nResult = nNumerator * xDenominator
if xResult % nResult == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
return xProduct == nProduct
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
return xProduct == nProduct
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let x = xNumerator * nDenominator
let y = xDenominator * nNumerator
if x % y == 0 {
return true
}
return false
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let x = xNumerator * nDenominator
let y = xDenominator * nNumerator
if x % y == 0 {
return true
}
return false
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xNumeratorTimesNDenominator = xNumerator * nDenominator
let xDenominatorTimesNNumerator = xDenominator * nNumerator
if xNumeratorTimesNDenominator % xDenominatorTimesNNumerator == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
if xProduct % nProduct == 0 {
return true
} else {
return false
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xNumerator = Int(x.components(separatedBy: "/")[0])!
let xDenominator = Int(x.components(separatedBy: "/")[1])!
let nNumerator = Int(n.components(separatedBy: "/")[0])!
let nDenominator = Int(n.components(separatedBy: "/")[1])!
let xProduct = xNumerator * nDenominator
let nProduct = nNumerator * xDenominator
if xProduct % nProduct == 0 {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
nums.sort { (num1, num2) -> Bool in
let sum1 = String(num1).reduce(0, { $0 + Int(String($1))! })
let sum2 = String(num2).reduce(0, { $0 + Int(String($1))! })
if sum1 == sum2 {
return nums.index(of: num1)! < nums.index(of: num2)!
}
return sum1 < sum2
}
return nums
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
nums.sort { (num1, num2) -> Bool in
let sum1 = String(num1).reduce(0, { $0 + Int(String($1))! })
let sum2 = String(num2).reduce(0, { $0 + Int(String($1))! })
if sum1 == sum2 {
return nums.index(of: num1)! < nums.index(of: num2)!
}
return sum1 < sum2
}
return nums
}
```
nums.sort { (num1, num2) -> Bool in // overlapping accesses to 'nums', but modification requires exclusive access; consider copying to a local variable
return nums.index(of: num1)! < nums.index(of: num2)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
return nums.index(of: num1)! < nums.index(of: num2)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted { (num1, num2) -> Bool in
let sum1 = String(num1).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
let sum2 = String(num2).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
return sum1 < sum2
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted { (num1, num2) -> Bool in
let sum1 = String(num1).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
let sum2 = String(num2).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
return sum1 < sum2
}
}
```
return result + Int(digit)! // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort { (num1, num2) -> Bool in
let sum1 = String(num1).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
let sum2 = String(num2).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
if sum1 < sum2 {
return true
} else if sum1 > sum2 {
return false
} else {
return result.index(of: num1)! < result.index(of: num2)!
}
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort { (num1, num2) -> Bool in
let sum1 = String(num1).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
let sum2 = String(num2).reduce(0, { (result, digit) -> Int in
return result + Int(digit)!
})
if sum1 < sum2 {
return true
} else if sum1 > sum2 {
return false
} else {
return result.index(of: num1)! < result.index(of: num2)!
}
}
return result
}
```
return result + Int(digit)! // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
}
```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 first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
}
```
let first = $0.description.reduce(0, { $0 + Int($1)! }) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
}
```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 first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
}
```
let first = $0.description.reduce(0, { $0 + Int($1)! }) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { (num1, num2) -> Bool in
let num1String = String(num1)
let num2String = String(num2)
let num1Array = num1String.map { Int(String($0))! }
let num2Array = num2String.map { Int(String($0))! }
let num1Sum = num1Array.reduce(0, +)
let num2Sum = num2Array.reduce(0, +)
if num1Sum == num2Sum {
return num1 < num2
} else {
return num1Sum < num2Sum
}
})
return sorted
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { (num1, num2) -> Bool in
let num1String = String(num1)
let num2String = String(num2)
let num1Array = num1String.map { Int(String($0))! }
let num2Array = num2String.map { Int(String($0))! }
let num1Sum = num1Array.reduce(0, +)
let num2Sum = num2Array.reduce(0, +)
if num1Sum == num2Sum {
return num1 < num2
} else {
return num1Sum < num2Sum
}
})
return sorted
}
```
var sorted = nums.sorted(by: { (num1, num2) -> Bool in // variable 'sorted' was never mutated; consider changing to 'let' constant
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted {
let first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
}
```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 first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
}
```
let first = $0.description.reduce(0, { $0 + Int($1)! }) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
var sorted = [Int]()
for i in 0..<nums.count {
for j in 0..<nums.count {
if nums[i] < nums[j] {
let temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
}
}
for i in 0..<nums.count {
sorted.append(nums[i])
}
return sorted
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
var sorted = [Int]()
for i in 0..<nums.count {
for j in 0..<nums.count {
if nums[i] < nums[j] {
let temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
}
}
for i in 0..<nums.count {
sorted.append(nums[i])
}
return sorted
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort { (num1: Int, num2: Int) -> Bool in
let sum1 = String(num1).reduce(0, { (sum, char) -> Int in
return sum + Int(String(char))!
})
let sum2 = String(num2).reduce(0, { (sum, char) -> Int in
return sum + Int(String(char))!
})
if sum1 == sum2 {
return result.index(of: num1)! < result.index(of: num2)!
}
return sum1 < sum2
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var result = nums
result.sort { (num1: Int, num2: Int) -> Bool in
let sum1 = String(num1).reduce(0, { (sum, char) -> Int in
return sum + Int(String(char))!
})
let sum2 = String(num2).reduce(0, { (sum, char) -> Int in
return sum + Int(String(char))!
})
if sum1 == sum2 {
return result.index(of: num1)! < result.index(of: num2)!
}
return sum1 < sum2
}
return result
}
```
result.sort { (num1: Int, num2: Int) -> Bool in // overlapping accesses to 'result', but modification requires exclusive access; consider copying to a local variable
return result.index(of: num1)! < result.index(of: num2)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
return result.index(of: num1)! < result.index(of: num2)! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
nums.sort {
let first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
return nums
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var nums = nums
nums.sort {
let first = $0.description.reduce(0, { $0 + Int($1)! })
let second = $1.description.reduce(0, { $0 + Int($1)! })
return first < second
}
return nums
}
```
let first = $0.description.reduce(0, { $0 + Int($1)! }) // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 == 1 && (num / 10) % 2 == 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 == 1 && (num / 10) % 2 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 != 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
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && isOdd(num: num) {
count += 1
}
}
return count
}
func isOdd(num: Int) -> Bool {
let firstDigit = num / 100
let lastDigit = num % 10
return firstDigit % 2 != 0 && lastDigit % 2 != 0
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && isOdd(num: num) {
count += 1
}
}
return count
}
func isOdd(num: Int) -> Bool {
let firstDigit = num / 100
let lastDigit = num % 10
return firstDigit % 2 != 0 && lastDigit % 2 != 0
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
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
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 == 1 && (num / 10) % 2 == 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 == 1 && (num / 10) % 2 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if (a[i] + a[j] + a[k]) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
func sortedListSum(lst: [String]) -> [String] {
var result = lst.filter { $0.count % 2 == 0 }
result.sort { $0.count < $1.count }
result.sort { $0 < $1 }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst.filter { $0.count % 2 == 0 }
result.sort { $0.count < $1.count }
result.sort { $0 < $1 }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var arr = lst
arr.sort()
arr.sort { $0.count < $1.count }
arr.sort { $0.count == $1.count && $0 < $1 }
arr.removeAll { $0.count % 2 != 0 }
return arr
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var arr = lst
arr.sort()
arr.sort { $0.count < $1.count }
arr.sort { $0.count == $1.count && $0 < $1 }
arr.removeAll { $0.count % 2 != 0 }
return arr
}
```
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.count < $1.count })
sortedList = sortedList.filter { $0.count % 2 == 0 }
return sortedList
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.count < $1.count })
sortedList = sortedList.filter { $0.count % 2 == 0 }
return sortedList
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result = result.sorted { $0.count < $1.count }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result = result.sorted { $0.count < $1.count }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.count < $1.count })
sortedList = sortedList.filter { $0.count % 2 == 0 }
return sortedList
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.count < $1.count })
sortedList = sortedList.filter { $0.count % 2 == 0 }
return sortedList
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = lst.sorted { $0.count < $1.count }
result = result.filter { $0.count % 2 == 0 }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst.sorted { $0.count < $1.count }
result = result.filter { $0.count % 2 == 0 }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var arr = lst
arr.sort { $0.count < $1.count }
arr.sort { $0.count == $1.count ? $0 < $1 : false }
arr.removeAll { $0.count % 2 != 0 }
return arr
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var arr = lst
arr.sort { $0.count < $1.count }
arr.sort { $0.count == $1.count ? $0 < $1 : false }
arr.removeAll { $0.count % 2 != 0 }
return arr
}
```
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.count < $1.count })
for i in 0..<sortedList.count {
if sortedList[i].count % 2 != 0 {
sortedList.remove(at: i)
}
}
return sortedList
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.count < $1.count })
for i in 0..<sortedList.count {
if sortedList[i].count % 2 != 0 {
sortedList.remove(at: i)
}
}
return sortedList
}
```
// Fatal error: Index out of range
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted { $0.count < $1.count }
var newList = [String]()
for i in sortedList {
if i.count % 2 == 0 {
newList.append(i)
}
}
return newList
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted { $0.count < $1.count }
var newList = [String]()
for i in sortedList {
if i.count % 2 == 0 {
newList.append(i)
}
}
return newList
}
```
var sortedList = lst.sorted { $0.count < $1.count } // variable 'sortedList' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = lst.filter { $0.count % 2 == 0 }
result.sort { $0.count < $1.count }
result.sort { $0 < $1 }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst.filter { $0.count % 2 == 0 }
result.sort { $0.count < $1.count }
result.sort { $0 < $1 }
return result
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: Your code here!
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: Your code here!
}
```
} // missing return in global function expected to return 'Int'
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: your code here
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: your code here
}
// Tests
assert(xOrY(n: 7, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 15, x: 8, y: 5) == 5, "Should return y")
assert(xOrY(n: 17, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 21, x: 8, y: 5) == 5, "Should return y")
assert(xOrY(n: 2, x: 34, y: 12) == 12, "Should return y")
assert(xOrY(n: 3, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 5, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 7, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 11, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 13, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 17, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 19, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 23, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 29, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 31, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 37, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 41, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 43, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 47, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 53, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 59, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 61, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 67, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 71, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 73, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 79, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 83, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 89, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n: 97, x: 34, y: 12) == 34, "Should return x")
assert(xOrY(n: 101, x: 8, y: 5) == 8, "Should return x")
assert(xOrY(n:
} // missing return in global function expected to return 'Int'
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: your code here
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: your code here
}
// Uncomment the line below when you're ready to try out your function
print(xOrY(n: 7, x: 34, y: 12))
```
} // missing return in global function expected to return 'Int'
func xOrY(n: Int, x: Int, y: Int) -> Int {
var i = 2
var isPrime = true
while i < n {
if n % i == 0 {
isPrime = false
break
}
i += 1
}
if isPrime {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
var i = 2
var isPrime = true
while i < n {
if n % i == 0 {
isPrime = false
break
}
i += 1
}
if isPrime {
return x
} else {
return y
}
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
break
}
}
if isPrime {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
break
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: Your code here
return 0
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
// TODO: Your code here
return 0
}
// Tests
print(xOrY(n: 7, x: 34, y: 12) == 34)
print(xOrY(n: 15, x: 8, y: 5) == 5)
print(xOrY(n: 1, x: 1, y: 0) == 0)
print(xOrY(n: 2, x: 1, y: 0) == 1)
print(xOrY(n: 3, x: 1, y: 0) == 1)
print(xOrY(n: 4, x: 1, y: 0) == 0)
print(xOrY(n: 5, x: 1, y: 0) == 1)
print(xOrY(n: 6, x: 1, y: 0) == 0)
print(xOrY(n: 7, x: 1, y: 0) == 1)
print(xOrY(n: 8, x: 1, y: 0) == 0)
print(xOrY(n: 9, x: 1, y: 0) == 0)
print(xOrY(n: 10, x: 1, y: 0) == 0)
print(xOrY(n: 11, x: 1, y: 0) == 1)
print(xOrY(n: 12, x: 1, y: 0) == 0)
print(xOrY(n: 13, x: 1, y: 0) == 1)
print(xOrY(n: 14, x: 1, y: 0) == 0)
print(xOrY(n: 15, x: 1, y: 0) == 0)
print(xOrY(n: 16, x: 1, y: 0) == 0)
print(xOrY(n: 17, x: 1, y: 0) == 1)
print(xOrY(n: 18, x: 1, y: 0) == 0)
print(xOrY(n: 19, x: 1, y: 0) == 1)
print(xOrY(n: 20, x: 1, y: 0) == 0)
print(xOrY(n: 21, x: 1, y: 0) == 0)
print(xOrY(n: 22, x: 1, y: 0) == 0)
print(xOrY(n: 23, x: 1, y: 0) == 1)
print(xOrY(n: 24, x: 1, y: 0) == 0)
print(xOrY(n: 25, x: 1, y: 0) == 0)
print(xOrY(n: 26, x: 1, y: 0) == 0)
print(xOrY(n: 27, x: 1, y: 0) == 0)
print(xOrY(n: 28, x: 1, y: 0) == 0)
print(xOrY(n: 29, x: 1, y: 0) == 1)
print(xOrY(n: 30, x: 1, y: 0) == 0)
print(xOrY(n: 31, x: 1, y: 0) == 1)
print(xOrY(n: 32, x: 1, y: 0) == 0)
print(xOrY(n: 33, x: 1, y: 0) == 0)
print(xOrY(n: 34, x: 1, y: 0) == 0)
print(xOrY(n: 35, x: 1, y: 0) == 0)
print(xOrY(n: 36, x
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
var isPrime = true
for i in 2..<n {
if n % i == 0 {
isPrime = false
}
}
if isPrime {
return x
} else {
return y
}
}
```
// Fatal error: Range requires lowerBound <= upperBound
func doubleTheDifference(lst: [Double]) -> Int {
var odd = 0
for i in lst {
if i % 2 != 0 && i > 0 {
odd += Int(i * i)
}
}
return odd
}
```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 odd = 0
for i in lst {
if i % 2 != 0 && i > 0 {
odd += Int(i * i)
}
}
return odd
}
```
if i % 2 != 0 && i > 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(num * num)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(num * num)
}
}
return sum
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var odd = 0
for i in lst {
if i % 2 != 0 && i > 0 {
odd += Int(i * i)
}
}
return odd
}
```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 odd = 0
for i in lst {
if i % 2 != 0 && i > 0 {
odd += Int(i * i)
}
}
return odd
}
```
if i % 2 != 0 && i > 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func doubleTheDifference(lst: [Double]) -> Int {
let oddNumbers = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
return oddNumbers.reduce(0) { $0 + Int($1 * $1) }
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
let oddNumbers = lst.filter { $0 > 0 && $0.truncatingRemainder(dividingBy: 1) == 0 }
return oddNumbers.reduce(0) { $0 + Int($1 * $1) }
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(num * num)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(num * num)
}
}
return sum
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 1 == 0 {
sum += Int(i * i)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 1 == 0 {
sum += Int(i * i)
}
}
return sum
}
```
if i > 0 && i % 1 == 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i >= 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i >= 0 && i.truncatingRemainder(dividingBy: 1) == 0 {
sum += Int(i * i)
}
}
return sum
}
```
// XCTAssertTrue failed
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 {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
let diff = abs(game[i] - guess[i])
result.append(diff)
}
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 {
let diff = abs(game[i] - guess[i])
result.append(diff)
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2])
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2])
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionStrength = 0.0
for extension in extensions {
let extensionStrength = Double(extension.uppercased().count) - Double(extension.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.0
for extension in extensions {
let extensionStrength = Double(extension.uppercased().count) - Double(extension.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 = Double(extension.uppercased().count) - Double(extension.count) // expected expression in list of expressions
let extensionStrength = Double(extension.uppercased().count) - Double(extension.count) // declaration is only valid at file scope
let extensionStrength = Double(extension.uppercased().count) - Double(extension.count) // expected '{' in extension
let extensionStrength = Double(extension.uppercased().count) - Double(extension.count) // consecutive statements on a line must be separated by ';'
let extensionStrength = Double(extension.uppercased().count) - Double(extension.count) // expected type name in extension declaration
strongestExtension = extension // expected expression in assignment
strongestExtension = extension // declaration is only valid at file scope
strongestExtensionStrength = extensionStrength // expected '{' in extension
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionWithStrength = [String: Int]()
for extension in extensions {
var cap = 0
var sm = 0
for char in extension {
if char.isUppercase {
cap += 1
} else if char.isLowercase {
sm += 1
}
}
extensionWithStrength[extension] = cap - sm
}
let strongest = extensionWithStrength.max { $0.value < $1.value }
return "\(className).\(strongest!.key)"
}
```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 extensionWithStrength = [String: Int]()
for extension in extensions {
var cap = 0
var sm = 0
for char in extension {
if char.isUppercase {
cap += 1
} else if char.isLowercase {
sm += 1
}
}
extensionWithStrength[extension] = cap - sm
}
let strongest = extensionWithStrength.max { $0.value < $1.value }
return "\(className).\(strongest!.key)"
}
```
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
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
func Strongest_Extension(className: String, extensions: [String]) -> String {
var strongestExtension = ""
var strongestExtensionName = ""
for extension in extensions {
let extensionName = extension.lowercased()
let extensionNameArray = Array(extensionName)
var cap = 0
var sm = 0
for letter in extensionNameArray {
if letter.isUppercase {
cap += 1
} else {
sm += 1
}
}
let extensionStrength = cap - sm
if strongestExtension == "" {
strongestExtension = extension
strongestExtensionName = extensionName
} else if strongestExtensionName == extensionName {
strongestExtension = extension
strongestExtensionName = extensionName
} else if strongestExtensionName != extensionName && extensionStrength > 0 {
strongestExtension = extension
strongestExtensionName = extensionName
}
}
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 strongestExtensionName = ""
for extension in extensions {
let extensionName = extension.lowercased()
let extensionNameArray = Array(extensionName)
var cap = 0
var sm = 0
for letter in extensionNameArray {
if letter.isUppercase {
cap += 1
} else {
sm += 1
}
}
let extensionStrength = cap - sm
if strongestExtension == "" {
strongestExtension = extension
strongestExtensionName = extensionName
} else if strongestExtensionName == extensionName {
strongestExtension = extension
strongestExtensionName = extensionName
} else if strongestExtensionName != extensionName && extensionStrength > 0 {
strongestExtension = extension
strongestExtensionName = extensionName
}
}
return "\(className).\(strongestExtension)"
}
```
for extension in extensions { // expected Sequence expression for for-each loop
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
let extensionName = extension.lowercased() // expected type name in extension declaration
let extensionName = extension.lowercased() // declaration is only valid at file scope
let extensionName = extension.lowercased() // consecutive statements on a line must be separated by ';'
let extensionName = extension.lowercased() // expected '{' in extension
let extensionName = extension.lowercased() // expected initial value after '='
strongestExtension = extension // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtensionName = extensionName // expected '{' in extension
strongestExtensionName = extensionName // cannot find type 'strongestExtensionName' in scope
strongestExtension = extension // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtensionName = extensionName // cannot find type 'strongestExtensionName' in scope
strongestExtensionName = extensionName // expected '{' in extension
strongestExtension = extension // declaration is only valid at file scope
strongestExtension = extension // expected expression in assignment
strongestExtensionName = extensionName // expected '{' in extension
strongestExtensionName = extensionName // cannot find type 'strongestExtensionName' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionName = ""
var extensionStrength = 0
for extension in extensions {
let extensionName = extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > extensionName.count {
extensionName = extensionName
extensionStrength = extensionStrength
}
}
return "\(className).\(extensionName)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionName = ""
var extensionStrength = 0
for extension in extensions {
let extensionName = extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > extensionName.count {
extensionName = extensionName
extensionStrength = extensionStrength
}
}
return "\(className).\(extensionName)"
}
```
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 extensionName = extension // expected initial value after '='
let extensionName = extension // declaration is only valid at file scope
let extensionName = extension // expected '{' in extension
let extensionName = extension // consecutive statements on a line must be separated by ';'
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 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 // 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 // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
```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 extensionWithMaxStrength = ""
var maxStrength = 0
for extension in extensions {
let extensionName = extension.lowercased()
let extensionNameWithoutUnderScore = extensionName.replacingOccurrences(of: "_", with: "")
let extensionNameWithoutUnderScoreAndDash = extensionNameWithoutUnderScore.replacingOccurrences(of: "-", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpace = extensionNameWithoutUnderScoreAndDash.replacingOccurrences(of: " ", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDot = extensionNameWithoutUnderScoreAndDashAndSpace.replacingOccurrences(of: ".", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDot.replacingOccurrences(of: "/", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlash.replacingOccurrences(of: "\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlash.replacingOccurrences(of: "\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\\\\\\\\\\\", with: "")
let extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash = extensionNameWithoutUnderScoreAndDashAndSpaceAndDotAndSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlashAndBackSlash.replacingOccurrences(of: "\\\\\\\\\\\\\\
XCTAssertTrue(Strongest_Extension(className: "Watashi", extensions: ["tEN", "niNE", "eIGHt8OKe"]) == "Watashi.eIGHt8OKe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Boku123", extensions: ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]) == "Boku123.YEs.WeCaNe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__YESIMHERE", extensions: ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]) == "__YESIMHERE.NuLl__") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "K", extensions: ["Ta", "TAR", "t234An", "cosSo"]) == "K.TAR") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__HAHA", extensions: ["Tab", "123", "781345", "--"]) == "__HAHA.123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "YameRore", extensions: ["HhAas", "okIWILL123", "WorkOut", "Fails", "--"]) == "YameRore.okIWILL123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "finNNalLLly", extensions: ["Die", "NowW", "Wow", "WoW"]) == "finNNalLLly.WoW") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "", extensions: ["Bb", "91245"]) == ".Bb") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Sp", extensions: ["671235", "Bb"]) == "Sp.671235") // cannot find 'Strongest_Extension' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionList = [String]()
for extension in extensions {
var extensionName = extension
for char in extensionName {
if char.isLowercase {
extensionName = extensionName.replacingOccurrences(of: String(char), with: "")
}
}
extensionList.append(extensionName)
}
let extensionList = extensionList.sorted { $0.count > $1.count }
return className + "." + extensionList[0]
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionList = [String]()
for extension in extensions {
var extensionName = extension
for char in extensionName {
if char.isLowercase {
extensionName = extensionName.replacingOccurrences(of: String(char), with: "")
}
}
extensionList.append(extensionName)
}
let extensionList = extensionList.sorted { $0.count > $1.count }
return className + "." + extensionList[0]
}
```
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
var extensionName = extension // consecutive statements on a line must be separated by ';'
var extensionName = extension // expected '{' in extension
var extensionName = extension // expected initial value after '='
var extensionName = extension // declaration is only valid at file scope
for char in extensionName { // expected type name in extension declaration
let extensionList = extensionList.sorted { $0.count > $1.count } // invalid redeclaration of 'extensionList'
```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 extensionList = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList2 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList3 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList4 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList5 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList6 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList7 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList8 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList9 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList10 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList11 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList12 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList13 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList14 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList15 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList16 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList17 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList18 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList19 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList20 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList21 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList22 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList23 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList24 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList25 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList26 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList27 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList28 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList29 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList30 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList31 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList32 = extensions.sorted(by: { $0.lowercased() > $1.lowercased() })
var extensionList33 = extensions.sorted(by: { $0.uppercased() < $1.uppercased() })
var extensionList34 = extensions.sorted(by: { $0.lowercased() < $1.lowercased() })
var extensionList35 = extensions.sorted(by: { $0.uppercased() > $1.uppercased() })
var extensionList36 = extensions.sorted(by: { $0.lower
XCTAssertTrue(Strongest_Extension(className: "Watashi", extensions: ["tEN", "niNE", "eIGHt8OKe"]) == "Watashi.eIGHt8OKe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Boku123", extensions: ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]) == "Boku123.YEs.WeCaNe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__YESIMHERE", extensions: ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]) == "__YESIMHERE.NuLl__") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "K", extensions: ["Ta", "TAR", "t234An", "cosSo"]) == "K.TAR") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__HAHA", extensions: ["Tab", "123", "781345", "--"]) == "__HAHA.123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "YameRore", extensions: ["HhAas", "okIWILL123", "WorkOut", "Fails", "--"]) == "YameRore.okIWILL123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "finNNalLLly", extensions: ["Die", "NowW", "Wow", "WoW"]) == "finNNalLLly.WoW") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "", extensions: ["Bb", "91245"]) == ".Bb") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Sp", extensions: ["671235", "Bb"]) == "Sp.671235") // cannot find 'Strongest_Extension' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var 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 Sequence expression for for-each loop
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
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 // 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 // declaration is only valid at file scope
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 // expected '{' in extension
strongestExtensionStrength = extensionStrength // cannot find type 'strongestExtensionStrength' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionName = ""
var extensionStrength = 0
for extension in extensions {
let extensionName = extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > extensionStrength {
extensionName = extensionName
extensionStrength = extensionStrength
}
}
return "\(className).\(extensionName)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var extensionName = ""
var extensionStrength = 0
for extension in extensions {
let extensionName = extension
let extensionStrength = extension.uppercased().count - extension.lowercased().count
if extensionStrength > extensionStrength {
extensionName = extensionName
extensionStrength = extensionStrength
}
}
return "\(className).\(extensionName)"
}
```
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 extensionName = extension // expected initial value after '='
let extensionName = extension // declaration is only valid at file scope
let extensionName = extension // expected '{' in extension
let extensionName = extension // consecutive statements on a line must be separated by ';'
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 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 // 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 // declaration is only valid at file scope
let extensionStrength = extension.uppercased().count - extension.lowercased().count // declaration is only valid at file scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.components(separatedBy: " ")
let classString = classArray.joined(separator: "_")
var extensionArray = [String]()
var extensionString = ""
for extension in extensions {
let extensionArray = extension.components(separatedBy: " ")
let extensionString = extensionArray.joined(separator: "_")
extensionArray.append(extensionString)
}
let extensionString = extensionArray.max(by: { $0.count < $1.count })
return "\(classString).\(extensionString!)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let classArray = className.components(separatedBy: " ")
let classString = classArray.joined(separator: "_")
var extensionArray = [String]()
var extensionString = ""
for extension in extensions {
let extensionArray = extension.components(separatedBy: " ")
let extensionString = extensionArray.joined(separator: "_")
extensionArray.append(extensionString)
}
let extensionString = extensionArray.max(by: { $0.count < $1.count })
return "\(classString).\(extensionString!)"
}
```
for extension in extensions { // expected Sequence expression for for-each loop
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected pattern
let extensionArray = extension.components(separatedBy: " ") // expected type name in extension declaration
let extensionArray = extension.components(separatedBy: " ") // expected '{' in extension
let extensionArray = extension.components(separatedBy: " ") // declaration is only valid at file scope
let extensionArray = extension.components(separatedBy: " ") // consecutive statements on a line must be separated by ';'
let extensionArray = extension.components(separatedBy: " ") // expected initial value after '='
let extensionString = extensionArray.max(by: { $0.count < $1.count }) // invalid redeclaration of 'extensionString'
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var a = a
var b = b
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
var b = b.characters.count
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()
for i in 0..<a.count {
let a = a.dropFirst(i)
let b = b.dropLast(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i)
let b = b.dropLast(i)
if a.contains(b) {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(b) {
return true
}
}
return false
}
```
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i)
let b = b.dropLast(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i)
let b = b.dropLast(i)
if a.contains(b) {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(b) {
return true
}
}
return false
}
```
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b = b
var a = a
var b
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i) + a.prefix(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i) + a.prefix(i)
if a.contains(b) {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(b) {
return true
}
}
return false
}
```
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i)
let b = b.dropLast(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<a.count {
let a = a.dropFirst(i)
let b = b.dropLast(i)
if a.contains(b) {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(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 {
let a = a.lowercased()
let b = b.lowercased()
for i in 0..<b.count {
let b = b.dropFirst(i) + b.prefix(i)
if a.contains(b) {
return true
}
}
return false
}
```
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = abs(num)
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = abs(num)
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var evenCount = 0
var oddCount = 0
for char in numString {
let digit = Int(String(char))!
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var evenCount = 0
var oddCount = 0
for char in numString {
let digit = Int(String(char))!
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var even = 0
var odd = 0
for char in numString {
if Int(String(char))! % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var even = 0
var odd = 0
for char in numString {
if Int(String(char))! % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = abs(num)
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = abs(num)
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(num)
var even = 0
var odd = 0
for char in str {
let digit = Int(String(char))!
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(num)
var even = 0
var odd = 0
for char in str {
let digit = Int(String(char))!
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var number = abs(num)
while number > 0 {
let digit = number % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
number /= 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 number = abs(num)
while number > 0 {
let digit = number % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
number /= 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var evenCount = 0
var oddCount = 0
for char in numString {
if Int(String(char))! % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var evenCount = 0
var oddCount = 0
for char in numString {
if Int(String(char))! % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var evenCount = 0
var oddCount = 0
for char in numString {
if Int(String(char))! % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let numString = String(num)
var evenCount = 0
var oddCount = 0
for char in numString {
if Int(String(char))! % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num != 0 {
let digit = num % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
num = num / 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num != 0 {
let digit = num % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
num = num / 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = abs(num)
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
var num = abs(num)
while num > 0 {
let digit = num % 10
if digit % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
num /= 10
}
return (evenCount, oddCount)
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var result = ""
var num = number
for (value, symbol) in romanNumerals {
while num >= value {
result += symbol
num -= value
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var result = ""
var num = number
for (value, symbol) in romanNumerals {
while num >= value {
result += symbol
num -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var num = number
for (index, numeral) in numerals.enumerated() {
while num >= numeral {
result += romanNumerals[index]
num -= numeral
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var num = number
for (index, numeral) in numerals.enumerated() {
while num >= numeral {
result += romanNumerals[index]
num -= numeral
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanString = ""
var num = number
for (index, numeral) in romanNumerals.enumerated() {
while num >= arabicNumerals[index] {
romanString += numeral
num -= arabicNumerals[index]
}
}
return romanString
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanString = ""
var num = number
for (index, numeral) in romanNumerals.enumerated() {
while num >= arabicNumerals[index] {
romanString += numeral
num -= arabicNumerals[index]
}
}
return romanString
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var result = ""
var num = number
for (value, symbol) in romanNumerals {
while num >= value {
result += symbol
num -= value
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var result = ""
var num = number
for (value, symbol) in romanNumerals {
while num >= value {
result += symbol
num -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var roman = ""
var num = number
for (value, symbol) in romanNumerals {
while num >= value {
roman += symbol
num -= value
}
}
return roman
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var roman = ""
var num = number
for (value, symbol) in romanNumerals {
while num >= value {
roman += symbol
num -= value
}
}
return roman
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var num = number
for (index, numeral) in numerals.enumerated() {
while num >= numeral {
result += romanNumerals[index]
num -= numeral
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var num = number
for (index, numeral) in numerals.enumerated() {
while num >= numeral {
result += romanNumerals[index]
num -= numeral
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I"
]
var result = ""
var num = number
for (value, numeral) in romanNumerals {
while num >= value {
result += numeral
num -= value
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I"
]
var result = ""
var num = number
for (value, numeral) in romanNumerals {
while num >= value {
result += numeral
num -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var result = ""
var number = number
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= value
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"]
var result = ""
var number = number
for (value, numeral) in romanNumerals {
while number >= value {
result += numeral
number -= value
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var number = number
for (index, numeral) in romanNumerals.enumerated() {
while number >= arabicNumerals[index] {
result += numeral
number -= arabicNumerals[index]
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var number = number
for (index, numeral) in romanNumerals.enumerated() {
while number >= arabicNumerals[index] {
result += numeral
number -= arabicNumerals[index]
}
}
return result
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var number = number
for (index, numeral) in romanNumerals.enumerated() {
while number >= arabicNumerals[index] {
result += numeral
number -= arabicNumerals[index]
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var result = ""
var number = number
for (index, numeral) in romanNumerals.enumerated() {
while number >= arabicNumerals[index] {
result += numeral
number -= arabicNumerals[index]
}
}
return result
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
}
return false
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let a2 = a * a
let b2 = b * b
let c2 = c * c
if a2 + b2 == c2 || a2 + c2 == b2 || b2 + c2 == a2 {
return true
} else {
return false
}
}
```
func findMax(words: [String]) -> String {
let words = words.map { $0.sorted() }
let max = words.max { $0.count < $1.count }
let maxCount = max?.count
let maxWords = words.filter { $0.count == maxCount }
let maxWord = maxWords.min { $0 < $1 }
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 {
let words = words.map { $0.sorted() }
let max = words.max { $0.count < $1.count }
let maxCount = max?.count
let maxWords = words.filter { $0.count == maxCount }
let maxWord = maxWords.min { $0 < $1 }
return maxWord ?? ""
}
```
let maxWord = maxWords.min { $0 < $1 } // binary operator '<' cannot be applied to two '[String.Element]' (aka 'Array<Character>') operands
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = 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 count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = 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 count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = 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 count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
for char in word {
if word.filter({$0 == char}).count == 1 {
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
for char in word {
if word.filter({$0 == char}).count == 1 {
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var unique = 0
for char in word {
if word.filter({$0 == char}).count == 1 {
unique += 1
}
}
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 {
var unique = 0
for char in word {
if word.filter({$0 == char}).count == 1 {
unique += 1
}
}
if unique > max {
max = unique
maxWord = word
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
for char in word {
if word.contains(char) {
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
var count = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
count += 1
}
}
if count > max {
max = 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 count = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
count += 1
}
}
if count > max {
max = 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 eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let carrotsLeft = remaining - need
if carrotsLeft < 0 {
return [total, 0]
} else {
return [total, carrotsLeft]
}
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let carrotsLeft = remaining - need
if carrotsLeft < 0 {
return [total, 0]
} else {
return [total, carrotsLeft]
}
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var carrotsEaten = number + need
var carrotsLeft = remaining - need
if carrotsLeft < 0 {
carrotsLeft = 0
}
return [carrotsEaten, carrotsLeft]
}
```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 carrotsEaten = number + need
var carrotsLeft = remaining - need
if carrotsLeft < 0 {
carrotsLeft = 0
}
return [carrotsEaten, carrotsLeft]
}
```
var carrotsEaten = number + need // variable 'carrotsEaten' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var carrots = number + need
var carrotsLeft = remaining - carrots
if carrotsLeft < 0 {
carrots = number + remaining
carrotsLeft = 0
}
return [carrots, carrotsLeft]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var carrots = number + need
var carrotsLeft = remaining - carrots
if carrotsLeft < 0 {
carrots = number + remaining
carrotsLeft = 0
}
return [carrots, carrotsLeft]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrotsLeft = remaining - need
if carrotsLeft < 0 {
total = number + remaining
carrotsLeft = 0
}
return [total, carrotsLeft]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrotsLeft = remaining - need
if carrotsLeft < 0 {
total = number + remaining
carrotsLeft = 0
}
return [total, carrotsLeft]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var left = remaining - need
if left < 0 {
total = number + remaining
left = 0
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var left = remaining - need
if left < 0 {
total = number + remaining
left = 0
}
return [total, left]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrotsLeft = remaining - need
if carrotsLeft < 0 {
total = number + remaining
carrotsLeft = 0
}
return [total, carrotsLeft]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrotsLeft = remaining - need
if carrotsLeft < 0 {
total = number + remaining
carrotsLeft = 0
}
return [total, carrotsLeft]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrotsLeft = remaining
if total > carrotsLeft {
total = carrotsLeft
carrotsLeft = 0
} else {
carrotsLeft -= total
}
return [total, carrotsLeft]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var carrotsLeft = remaining
if total > carrotsLeft {
total = carrotsLeft
carrotsLeft = 0
} else {
carrotsLeft -= total
}
return [total, carrotsLeft]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
if left < 0 {
return [total, 0]
} else {
return [total, left]
}
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
if left < 0 {
return [total, 0]
} else {
return [total, left]
}
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var left = remaining - need
if left < 0 {
total = total + left
left = 0
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var left = remaining - need
if left < 0 {
total = total + left
left = 0
}
return [total, left]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var carrots = number + need
var carrotsLeft = remaining - carrots
if carrotsLeft < 0 {
carrots = number + remaining
carrotsLeft = 0
}
return [carrots, carrotsLeft]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var carrots = number + need
var carrotsLeft = remaining - carrots
if carrotsLeft < 0 {
carrots = number + remaining
carrotsLeft = 0
}
return [carrots, carrotsLeft]
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var stack = [Int]()
for (index, operator) in operators.enumerated() {
let operand1 = operands[index]
let operand2 = operands[index + 1]
switch operator {
case "+":
stack.append(operand1 + operand2)
case "-":
stack.append(operand1 - operand2)
case "*":
stack.append(operand1 * operand2)
case "//":
stack.append(operand1 / operand2)
case "**":
stack.append(operand1 ** operand2)
default:
break
}
}
return stack.last ?? 0
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var stack = [Int]()
for (index, operator) in operators.enumerated() {
let operand1 = operands[index]
let operand2 = operands[index + 1]
switch operator {
case "+":
stack.append(operand1 + operand2)
case "-":
stack.append(operand1 - operand2)
case "*":
stack.append(operand1 * operand2)
case "//":
stack.append(operand1 / operand2)
case "**":
stack.append(operand1 ** operand2)
default:
break
}
}
return stack.last ?? 0
}
```
for (index, operator) in operators.enumerated() { // expected '{' to start the body of for-each loop
for (index, operator) in operators.enumerated() { // expected 'in' after for-each pattern
for (index, operator) in operators.enumerated() { // expected Sequence expression for for-each loop
for (index, operator) in operators.enumerated() { // expected pattern
switch operator { // expected operator name in operator declaration
switch operator { // expected expression in 'switch' statement
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 0..<operators.count {
switch operators[i] {
case "+":
result += operands[i + 1]
case "-":
result -= operands[i + 1]
case "*":
result *= operands[i + 1]
case "//":
result = result / operands[i + 1]
case "**":
result = Int(pow(Double(result), Double(operands[i + 1])))
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isLowercase {
result += String(i).uppercased()
} else {
result += String(i).lowercased()
}
} else {
result += String(i)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isLowercase {
result += String(i).uppercased()
} else {
result += String(i).lowercased()
}
} else {
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(char).lowercased()
}
} else {
result += String(char)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(char).lowercased()
}
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(char).lowercased()
}
} else {
result += String(char)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLowercase {
result += String(char).uppercased()
} else {
result += String(char).lowercased()
}
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUppercase {
result += String(char).lowercased()
} else {
result += String(char).uppercased()
}
} else {
result += String(char)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUppercase {
result += String(char).lowercased()
} else {
result += String(char).uppercased()
}
} else {
result += String(char)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += String(i).lowercased()
} else {
result += String(i).uppercased()
}
} else {
result += String(i)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += String(i).lowercased()
} else {
result += String(i).uppercased()
}
} else {
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUppercase {
result.append(char.lowercased())
} else {
result.append(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 {
if char.isUppercase {
result.append(char.lowercased())
} else {
result.append(char.uppercased())
}
} else {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += i.lowercased()
} else {
result += i.uppercased()
}
} else {
result += String(i)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += i.lowercased()
} else {
result += i.uppercased()
}
} else {
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += String(i).lowercased()
} else {
result += String(i).uppercased()
}
} else {
result += String(i)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += String(i).lowercased()
} else {
result += String(i).uppercased()
}
} else {
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isUppercase {
result += String(i.lowercased())
} else {
result += String(i.uppercased())
}
} else {
result += String(i)
}
}
if result.isEmpty {
return String(s.reversed())
} else {
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 i in s {
if i.isLetter {
if i.isUppercase {
result += String(i.lowercased())
} else {
result += String(i.uppercased())
}
} else {
result += String(i)
}
}
if result.isEmpty {
return String(s.reversed())
} else {
return result
}
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isLowercase {
result += String(i).uppercased()
} else {
result += String(i).lowercased()
}
} else {
result += String(i)
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for i in s {
if i.isLetter {
if i.isLowercase {
result += String(i).uppercased()
} else {
result += String(i).lowercased()
}
} else {
result += String(i)
}
}
return result
}
```
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
return data.md5
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
return data.md5
}
```
return data.md5 // value of type 'Data' has no member 'md5'
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard text.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
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.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
let digest = Insecure.MD5.hash(data: data) // cannot find 'Insecure' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard text.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
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.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
let digest = Insecure.MD5.hash(data: data) // cannot find 'Insecure' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest) // 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard text.count > 0 else { return nil }
let data = text.data(using: .utf8)!
let digest = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return 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.count > 0 else { return nil }
let data = text.data(using: .utf8)!
let digest = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return digest.map { String(format: "%02x", $0) }.joined()
}
```
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard text.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
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.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
let digest = Insecure.MD5.hash(data: data) // cannot find 'Insecure' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard text.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
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.count > 0 else {
return nil
}
let data = text.data(using: .utf8)!
let digest = Insecure.MD5.hash(data: data)
return digest.map { String(format: "%02hhx", $0) }.joined()
}
```
let digest = Insecure.MD5.hash(data: data) // cannot find 'Insecure' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest) // 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
CC_MD5(data.withUnsafeBytes { $0 }, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0.baseAddress!.assumingMemoryBound(to: UInt8.self) }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0.baseAddress!.assumingMemoryBound(to: UInt8.self) }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```
CC_MD5(data.withUnsafeBytes { $0.baseAddress!.assumingMemoryBound(to: UInt8.self) }, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
// XCTAssertTrue failed
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0.baseAddress!.assumingMemoryBound(to: UInt8.self) }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard let data = text.data(using: .utf8) else { return nil }
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(data.withUnsafeBytes { $0.baseAddress!.assumingMemoryBound(to: UInt8.self) }, CC_LONG(data.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
```
CC_MD5(data.withUnsafeBytes { $0.baseAddress!.assumingMemoryBound(to: UInt8.self) }, CC_LONG(data.count), &digest) // 'CC_MD5' was deprecated in macOS 10.15: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound